#!/bin/sh

while [ $# -gt 0 ];
do
key="$1"
case $key in
    -h|--help)
    HELP="1"
    shift # past argument
    ;;
    -n|--project-name)
    PROJNAME="$2"
    shift # past argument
    shift # past value
    ;;
    -t|--project-type)
    PROJTYPE="$2"
    shift
    shift
    ;;
    -u|--repo-url)
    REPOURL="$2"
    shift # past argument
    shift # past value
    ;;
    *)    # unknown option
    shift
    ;;
esac
done

if [ -n "$HELP" ] || [ -z "$PROJNAME" ]; then
    printf "Visit https://github.com/caseyjohnsonwv/easy-heroku-flask for help.\n"
    exit
fi

mkdir "$PROJNAME" >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
    printf "Unable to create directory '$PROJNAME'- is this valid?\n"
    exit
fi
cd "$PROJNAME"

printf "Cloning app template from https://github.com/caseyjohnsonwv/easy-heroku-flask.\n"
git clone https://github.com/caseyjohnsonwv/easy-heroku-flask .ehfqs -q
mv .ehfqs/quickstarts/base/* .
if [ -z "$PROJTYPE" ]; then
    mv .ehfqs/quickstarts/no-type/* .
    mv .ehfqs/quickstarts/no-type/.* . >/dev/null 2>&1
elif [ ! -d ".ehfqs/quickstarts/$PROJTYPE" ]; then
    printf "Unable to find app template '$PROJTYPE'- is this valid?\n"
    exit
else
    mv .ehfqs/quickstarts/"$PROJTYPE"/* .
    mv .ehfqs/quickstarts/"$PROJTYPE"/.* . >/dev/null 2>&1
fi
rm -rf .ehfqs
echo ".env\nenv.py\nenv.pyc\n__pycache__" > .gitignore

printf "Installing Heroku/Flask requirements.\n"
python3 -m pip install -r requirements.txt --no-cache-dir --upgrade >/dev/null 2>&1

if [ -n "$REPOURL" ]; then
    printf "Syncing new project to remote repository.\n"
    git init  >/dev/null 2>&1
    git add . >/dev/null 2>&1
    git commit -m "initial commit" >/dev/null 2>&1
    git remote add origin "$REPOURL" >/dev/null 2>&1
    git push origin master >/dev/null 2>&1
    if [ "$?" -ne "0" ]; then
      printf "Failed to push to '$REPOURL'- is this valid?\n"
      exit
    fi
fi

printf "Heroku/Flask project '$PROJNAME' created.\n"
