#!/bin/bash
programname=$0
project_root=$(find ~ -type d \( -name '.*' -o -name 'Library' \) -prune -o -type d -name 'mobile-backend' -exec echo "{}" \; -quit 2>/dev/null)

function run {
    cd ${project_root}/app
    python .
}

function save_spec {
    curl http://localhost:21000/openapi.json -O  api/openapi.json
    echo "Saved."
}

function activate_pyenv {
    venv_name="${HOME}/.pyenv/versions/ukay-delivery-backend"
    if [ -d "$venv_name" ]; then
        if [ -f "$venv_name/bin/activate" ] || [ -f "$venv_name/Scripts/activate" ]; then
            echo "The venv exists. Activate it by running the following command:"
            echo "source $venv_name/bin/activate"
            exit
        fi
    else
        echo "$venv_name directory does not exist."
        exit
    fi
}

function install_requirements {
    pip install -r requirements.txt
}

function run_tests {
    cd ${project_root}/app
    python -m pytest -s ../tests
}

function setup {
    unameOut="$(uname -s)"
    case "${unameOut}" in
        Linux*)     machine=Linux;;
        Darwin*)    machine=Mac;;
        CYGWIN*)    machine=Cygwin;;
        MINGW*)     machine=MinGw;;
        MSYS_NT*)   machine=Git;;
        *)          machine="UNKNOWN:${unameOut}"
    esac
    
    
    python_version=""
    echo "Checking for Python installation"
    
    if command -v python3 &>/dev/null; then
        python_version=python3
        elif command -v python2 &>/dev/null; then
        python_version=python
    fi
    
    if [ -n "$python_version" ]; then
        ${python_version} --version
    else
        echo "A valid Python installation was not found. Please re-install then try running the script again."
    fi
    
    
    if [ "$machine" = "Mac" ]; then
        echo "Script is running on Mac. Running Mac setup"
        echo "Checking for pyenv installation"
        if command -v pyenv &>/dev/null; then
            echo "pyenv is installed."
        else
            echo "pyenv is not installed. Checking for homebrew"
            if command -v brew &>/dev/null; then
                echo "Homebrew is installed. Installing pyenv."
                brew install pyenv -y
                brew install pyenv-virtualenv -y
                echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
                echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"'  >> ~/.zshrc
                echo 'eval "$(pyenv init -)"'  >> ~/.zshrc
            else
                echo "Homebrew is not installed. Please install Homebrew then try running this script again."
                exit
                
            fi
        fi
        echo "Pyenv setup completed. Installing project requirements."
        pyenv install 3.11.0
        pyenv global 3.11.0
        pyenv virtualenv ukay-delivery-backend
        pyenv activate ukay-delivery-backend
        if [ -n "$VIRTUAL_ENV" ]; then
            pip install -r requirements.txt
        else
            echo "An error occured while activating the virtual environment. Please complete the setup manually."
            exit
        fi
    else
        echo "Unsupported Machine detected. Please proceed with manual install according to your OS."
        exit
    fi
    echo 'alias ukay='${project_root}'/scripts/core.sh' >> ~/.zshrc
    echo '================================================================'
    echo "A new alias has been added to your .zshrc file. To run any other commands in this script, simply type ukay -h"
    echo '================================================================'
    echo "Setup was successfully completed."
}

function usage {
    echo "usage: $programname [-h | help] [-a | --activate-pyenv] [-r | --run] [-i | --install-reqs] [-c | --clean-setup] [-s | --save] [-t | --test]"
    echo "Multipurpose script that aides in automating some processes that will be commonly used for back-end development."
    echo "  -h, --help              Diplsay this message"
    echo "  -a, --activate-pyenv    Activate the virtual environment"
    echo "  -r, --run               Run development server on port 21000"
    echo "  -i, --install-reqs      Install project dependencies"
    echo "  -c, --clean-setup       Run development environment setup (First time use only)"
    echo "  -s, --save              Save a local copy of the OpenAPI spec file"
    echo "  -t, --test              Run tests located in current directory"
    exit 1
}

while [ $# -gt 0 ]; do
    case $1 in
        -a | --activate-pyenv)
            activate_pyenv
            break
        ;;
        -s | --save)
            save_spec
            break
        ;;
        -c | --clean-setup)
            setup
            break
        ;;
        -r | --run)
            run
            break
        ;;
        -h | --help)
            usage
        ;;
        -i | --install-reqs)
            install_requirements
            break
        ;;
        -t | --test)
            run_tests
            break
        ;;
        *)
            usage
        ;;
    esac
done
shift "$(($OPTIND -1))"