#!/bin/bash

CLI_VERSION="0.9.6"

BIN_DIR=$(dirname $0)

if [ -f $BIN_DIR/spry.php ]
then
   SPRY_DIR=$(dirname $BIN_DIR)
else
   SPRY_DIR=$(dirname $BIN_DIR)/ggedde/spry-cli
fi

for arg in "$@"
do
    if [ "$arg" == "version" ] || [ "$arg" == "v" ] || [ "$arg" == "-v" ] || [ "$arg" == "--version" ] || [ "$arg" == "-h" ] || [ "$arg" == "--help" ]
    then
        echo "Spry-Cli -v $CLI_VERSION"
    fi

    if [ "$1" == "init" ] || [ "$1" == "i" ]
    then
        if [ -d 'spry' ]
        then
            echo 'The folder "spry" already exists.'
            exit
        fi
        cp -r $SPRY_DIR/example_project spry

        if [ $2 ] && [ "$2" != "" ]
        then
            if [ -d $2 ]
            then
                echo "The public folder '$2' already exists."
                exit
            fi
            mkdir $2
            echo "<?php

include dirname(__DIR__).'/vendor/autoload.php';
include dirname(__DIR__).'/spry/init.php';

" >> "$2/index.php";

            php $SPRY_DIR/src/SpryCli.php "$@"
            echo ''

        fi
    fi

    if [ "$1" == "up" ] || [ "$1" == "u" ]
    then
        if [ "$2" != "" ] && [ -d $2 ]
        then
            echo ''
            php $SPRY_DIR/src/SpryCli.php "$@"
            php -S localhost:8000 -t $2 &>/dev/null
            echo ''
            echo 'Spry Server Closed.'
            exit
        fi

        if [ ! $2 ] || [ $2 == "" ]
        then
            if [ -f "$PWD/vendor/autoload.php" ] && [ -f "$PWD/spry/init.php" ]
            then
                echo ''
                php $SPRY_DIR/src/SpryCli.php "$@"
                php -S localhost:8000 $SPRY_DIR/server/up.php &>/dev/null
                echo ''
                echo 'Spry Server Closed.'
                exit
            else
                printf "\e[31;4mERROR:\e[0m Spry Server Could not find vendor/autoload.php or spry/init.php\nMake sure you run 'spry up' in your root Project directory that contains both vendor/autoload.php and spry/init.php\nOr run it with your endpoint folder 'spry up {public_dir}' that contains your index.php file."
                echo ""
                exit
            fi
        fi
    fi
done

php $SPRY_DIR/src/SpryCli.php "$@"
echo ''

exit
