#!/bin/bash
# Author: Evan Hemsley
# Usage: ./install.sh

# This file is heavily borrowed from Caleb Cornett's template install script.

# Get the directory of this script
MY_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# Checks if git is installed
function checkGit()
{
    git --version > /dev/null 2>&1
    if [ ! $? -eq 0 ]; then
        echo >&2 "ERROR: Git is not installed. Please install git to download FNA."
        exit 1
    fi
}

# Pulls FNA from the git master branch
function pullFNA()
{
    checkGit
    echo "Updating to the latest git version of FNA..."
	git submodule update --init --recursive
	if [ $? -eq 0 ]; then
		echo "Finished updating!"
	else
		echo >&2 "ERROR: Unable to update."
		exit 1
	fi
}

# Downloads and extracts prepackaged archive of native libraries ("fnalibs")
function getLibs()
{
    # Downloading
    echo "Downloading latest fnalibs..."
    curl http://fna.flibitijibibo.com/archive/fnalibs.tar.bz2 > "$MY_DIR/fnalibs.tar.bz2"
    if [ $? -eq 0 ]; then
        echo "Finished downloading!"
    else
        >&2 echo "ERROR: Unable to download successfully."
        exit 1
    fi

    # Decompressing
    echo "Decompressing fnalibs..."
    mkdir -p $MY_DIR/fnalibs
    tar xjC $MY_DIR/fnalibs -f $MY_DIR/fnalibs.tar.bz2
    if [ $? -eq 0 ]; then
        echo "Finished decompressing!"
        echo ""
        rm $MY_DIR/fnalibs.tar.bz2
    else
        >&2 echo "ERROR: Unable to decompress successfully."
        exit 1
    fi
}

getLibs

read -p "Enter your project name or 'exit' to quit: " newProjectName
if [[ $newProjectName = 'exit' || -z "$newProjectName" ]]; then
    exit 1
fi

# copy everything into new dir
NEW_PROJECT_DIR="$MY_DIR/../$newProjectName"
cp -R $MY_DIR $NEW_PROJECT_DIR

cd $NEW_PROJECT_DIR
files=(ProjectName.Core.sln ProjectName.Framework.sln .gitignore ProjectName/ProjectName.Core.csproj ProjectName/ProjectName.Framework.csproj ProjectName/ProjectNameGame.cs ProjectName/Program.cs .vscode/tasks.json .vscode/launch.json)
for file in "${files[@]}"; do
    sed -i -e "s/ProjectName/$newProjectName/g" "./$file"
done

mv ./ProjectName.Core.sln "./$newProjectName.Core.sln"
mv ./ProjectName.Framework.sln "./$newProjectName.Framework.sln"
mv ./ProjectName/ProjectName.Core.csproj "./ProjectName/$newProjectName.Core.csproj"
mv ./ProjectName/ProjectName.Framework.csproj "./ProjectName/$newProjectName.Framework.csproj"
mv ./ProjectName/ProjectNameGame.cs ./ProjectName/${newProjectName}Game.cs
mv ./ProjectName "./$newProjectName"
rm ./install.sh

echo "Project $newProjectName created at $(readlink -f $NEW_PROJECT_DIR)"