VENV_FOLDER_PATH="$(dirname "${VIRTUAL_ENV:-./}")"
VENV_FOLDER_NAME="$(basename "${VIRTUAL_ENV:-.venv}")"

[ -z "${VIRTUAL_ENV}" ] && OPERATION=c || OPERATION=d

help() {
    echo "USAGE:"
    echo "    venv [OPTIONS] [<VENV_FOLDER_PATH>]"
    echo
    echo "ARGS:"
    echo "    VENV_FOLDER_PATH           Folder containing virtual environment"
    echo
    echo "OPTIONS:"
    echo "    -c, --create               Create virtual environment"
    echo "    -d, --deactivate           Exit virtual environment"
    echo "    -f, --folder <name>        Specify venv folder name"
    echo "    -h, --help                 Print this message"
    echo "    -r, --remove               Deactivate and remove virtual environment"
}


remove() {
    [ -n "${VIRTUAL_ENV}" ] && deactivate
    rm -rf "${VENV_FOLDER}"
}


create_or_activate() {
    # shellcheck disable=SC1091
    if [ -d "${VENV_FOLDER}" ]; then
        source "${VENV_FOLDER}/bin/activate"
    else
        python3 -m venv "${VENV_FOLDER}"
        source "${VENV_FOLDER}/bin/activate"
    fi
}


while [ "$#" -gt 0 ]; do
    case "$1" in
        '-c'|'--create') OPERATION=c;;
        '-d'|'--deactivate') OPERATION=d; return;;
        '-r'|'--remove') OPERATION=r;;
        '-f'|'--folder') shift; VENV_FOLDER_PATH="$1";;
        -*) help; return;;
        *) VENV_FOLDER_NAME="$1";;
    esac
    shift
done


VENV_FOLDER="${VENV_FOLDER_PATH}/${VENV_FOLDER_NAME}"


# shellcheck disable=SC2015
case "${OPERATION}" in
    c) [ -z "${VIRTUAL_ENV}" ] && create_or_activate || help >&2;;
    d) [ -n "${VIRTUAL_ENV}" ] && deactivate         || help >&2;;
    r) [ -d "${VENV_FOLDER}" ] && remove             || help >&2;;
esac

# vim: ft=sh
