#!/bin/bash

set +e

if [ $# -lt 3 ]; then
    cat >&2 <<EOF
Usage:
  $0 [-d] <packages|requirements.txt|-> <venv|->
     <command> [args...]

Options:
  -d    Create/update the virtual environment only.
        Do not execute the command.

Parameters:
  packages
        Packages to install with pip.
        Example: "requests flask"

  requirements.txt
        Path to a requirements file.

  -
        Auto-detect requirements file:
        <script>-requirements.txt

  venv
        Virtual environment name.

  -
        Auto-generate venv path:
        <script_dir>/.venv/<script_name>

Examples:
  $0 requests myenv test.py

  $0 "requests flask" myenv python -V

  $0 requirements.txt myenv test.py arg1 arg2

  $0 - myenv test.py

  $0 - - test.py

  $0 -d - myenv test.py
EOF
    exit 1
fi

DONT_RUN=0

if [ "$1" == "-d" ]; then
    DONT_RUN=1
    shift
fi

PACKAGE_INSTALL=$1
shift
ENV_NAME=$1
shift

FILE=$(basename -- "$1")

if [ "$PACKAGE_INSTALL" == "-" ]; then
    PACKAGE_INSTALL="$(dirname -- "$1")/${FILE%.*}-requirements.txt"    
fi

# Directory pip runs from, so relative paths in a requirements file
# (./lib, -e ../pkg, -r other.txt...) resolve against the file, not the cwd
PIP_DIR=.
if [[ "$PACKAGE_INSTALL" == *requirements.txt ]]; then
    PIP_DIR=$(dirname -- "$PACKAGE_INSTALL")
    if type envsubst >/dev/null 2>&1; then
        PACKAGE_INSTALL=$(envsubst < "$PACKAGE_INSTALL")
    else
        PACKAGE_INSTALL=$(cat "$PACKAGE_INSTALL")
    fi
fi

if [ "$ENV_NAME" == "-" ]; then
    ENV_NAME=$(dirname -- "$1")/.venv/${FILE%.*}
elif [[ ! "$ENV_NAME" =~ ^/ ]]; then
    ENV_NAME=~/.spython_venvs/$ENV_NAME
fi

if [ ! -d "$ENV_NAME" ]; then
    mkdir -p "$ENV_NAME"
fi

# Resolve to an absolute path now that the directory exists (portable, no realpath needed)
ENV_NAME=$(cd "$ENV_NAME" && pwd)

# Bytecode cache lives inside the venv; Python creates the directory on first write
export PYTHONPYCACHEPREFIX="$ENV_NAME/pycache"
ENV_LOCK=$ENV_NAME.lock

PACKAGE_INSTALLED_FILE=$ENV_NAME/bin/requirements.txt

# True when the venv is missing or was built from other requirements
needs_install() {
    [ ! -f "$PACKAGE_INSTALLED_FILE" ] || [ "$PACKAGE_INSTALL" != "$(cat "$PACKAGE_INSTALLED_FILE")" ]
}

# Take the venv's lock on fd 200, creating the lock file if needed.
# The file is deleted on release, so a waiter may wake up holding a lock on
# an unlinked file while a newcomer locks a fresh one at the same path: both
# would install at once. Retry until the locked file is the one at the path.
acquire_lock() {
    while true; do
        { exec 200>>"$ENV_LOCK"; } 2>/dev/null || return 1
        flock 200 || return 1
        if [ /dev/fd/200 -ef "$ENV_LOCK" ]; then
            return 0
        fi
        exec 200>&-
    done
}

# Delete the lock file while still holding the lock, then release it
release_lock() {
    rm -f "$ENV_LOCK"
    exec 200>&-
}

# The lock is only taken when an install looks needed, so a normal run with
# an up-to-date venv never creates, takes or deletes the lock file. The check
# is repeated under the lock, since another process may have just installed.
if needs_install; then
    if ! acquire_lock; then
        echo "failed acquiring lock " "$ENV_LOCK" >&2
        exit 1
    fi
    trap release_lock EXIT

    if needs_install; then
        rm -Rf "$ENV_NAME"
        mkdir -p "$ENV_NAME"

        python3 -m venv "$ENV_NAME"
        if [ $? != 0 ]; then
            echo "failed creating venv at " "$ENV_NAME" >&2
            rm -Rf "$ENV_NAME"
            exit 1
        fi

        source "$ENV_NAME/bin/activate"

        # Make setuptools write .egg-info dirs into the venv instead of the
        # source tree of editable installs (-e ../pkg)
        mkdir -p "$ENV_NAME/egg-info"
        printf '[egg_info]\negg_base = %s\n' "$ENV_NAME/egg-info" > "$ENV_NAME/setuptools.cfg"

        if [[ -n $PACKAGE_INSTALL ]]; then
            # $PACKAGE_INSTALL left unquoted on purpose: it must split into separate pip args
            (cd "$PIP_DIR" && DIST_EXTRA_CONFIG="$ENV_NAME/setuptools.cfg" pip install $PACKAGE_INSTALL >/dev/null 2>/dev/null)
        fi
        if [ $? != 0 ]; then
            echo "failed installing packages: " "$PACKAGE_INSTALL" >&2
            rm -Rf "$ENV_NAME"
            exit 1
        fi
        echo -e "$PACKAGE_INSTALL" > "$PACKAGE_INSTALLED_FILE"
    fi

    release_lock
    trap - EXIT
fi

set -e

if [ "$DONT_RUN" -eq 1 ]; then
    exit 0
elif [ -f "$PACKAGE_INSTALLED_FILE" ]; then
    source "$ENV_NAME/bin/activate"

    if [[ "$1" == *.py ]] || head -n1 "$1" 2>/dev/null | grep -q spython; then
        python3 "$@"
    else
        "$@"
    fi
fi
