#!/usr/bin/env bash
set -eo pipefail

function initialize_venv() {
    echo "Setting up the development environment..."
    python -m venv venv
    echo "Activating venv..."
    source venv/bin/activate
    echo "Upgrading venv pip..."
    pip install -q --upgrade pip
    echo "Installing dependencies..."
    pip install -q -r requirements.txt
    echo "Done."
}

function update_venv() {
    echo "Updating venv..."
    echo "Checking if venv exists..."
    if [ ! -e venv ]; then
        echo "No Virtual Environment found, exiting..."
        exit
    fi

    echo "Checking for active virtual env..."
    if [ -n "$VIRTUAL_ENV" ]; then
        echo "found active Virtual env $VIRTUAL_ENV, deactivating..."
        deactivate
    fi

    echo "Activating venv..."
    source venv/bin/activate
    echo "Upgrading pip..."
    pip install -q --upgrade pip
    echo "Installing dependencies..."
    pip install -q -r requirements.txt
    echo "Done."
}

function clean_venv() {
    echo "Cleaning Development environment..."
    echo "Checking for active virtual env..."
    if [ -n "$VIRTUAL_ENV" ]; then
        echo "found active Virtual env $VIRTUAL_ENV, deactivating..."
        deactivate
    fi

    if [ -e venv ]; then
        echo "Removing virtual env venv..."
        rm -rf venv/
        echo "Done."
        exit
    fi
    echo "No virtual environment called venv found."
    echo "Nothing to do."

}


# Main section
if [ "$#" == 0 ]; then
    if [ -e venv ]; then
        echo "There is nothing to do. Use 'update' to update the development environment or 'clean' to remove the environment."
        exit
    fi
    initialize_venv
    exit

elif [ "$1" == "update" ]; then
    update_venv
    exit

elif [ "$1" == "clean" ]; then
    clean_venv
    exit

else
    echo "Unknown option. Use 'update' to update the venv and use 'clean' to remove the venv."
    exit
fi
