#!/usr/bin/env bash
#
# inve - activate a virtual environment in a subshell
#
# search up for common virtual environment names.
# activate in a subshell when one is found. otherwise, offer to create one.
#
# ---
# source: https://github.com/awdeorio/dotfiles

progname=$(basename "$0")
# virtual environment search path, basenames only, space separated
VENVPATH=".venv venv env"

# stop on errors
set -eu

# help
if [ "${1-}" = "-h" ] || [ "${1-}" = "--help" ]; then
  cat <<EOF
Usage: ${progname} [virtual_env]

Activate a virtual environment in a subshell.

Examples:
  inve        Search up for virtual env then activate or create
  inve VENV   Activate or create virtual env VENV
EOF
  exit
fi

# parse virtual env specified as an arg
if [ -n "${1-}" ]; then
  VIRTUAL_ENV="$1"
fi

# if no virtual env was provided as an arg, search up the directory tree
if [ -z "${VIRTUAL_ENV-}" ]; then
  DIR=$(pwd)
  while true; do
    for V in ${VENVPATH}; do
      TEST_VIRTUAL_ENV="${DIR%/}/${V%/}"
      if [ -e "${TEST_VIRTUAL_ENV}/bin/activate" ]; then
        VIRTUAL_ENV="${TEST_VIRTUAL_ENV}"
        break 2
      fi
    done

    # stop at the root
    if [ "${DIR}" = "/" ]; then
      break
    fi

    # move up one directory
    DIR=$(dirname "${DIR}")
  done
fi

# no virtual env provided as arg and not found
if [ -z "${VIRTUAL_ENV-}" ]; then
  VIRTUAL_ENV="$(pwd)/.venv"
fi

# virtual environment not found, offer to create one
if ! test -d "${VIRTUAL_ENV}"; then
  BASENAME=$(basename "${VIRTUAL_ENV}")
  echo "Virtual environment not found."
  printf '%s' "Create ${BASENAME} ? [yn]: "
  # read -p "Create ${BASENAME} ? [yn]: " -n 1 -r
  read -r REPLY
  echo
  case "${REPLY}" in
    ^[Yy]$)
      echo "python3 -m venv ${VIRTUAL_ENV}"
      python3 -m venv "${VIRTUAL_ENV}"
      echo "pip install --upgrade --quiet pip setuptools wheel"
      "${VIRTUAL_ENV}/bin/pip" install --upgrade --quiet pip setuptools wheel
      ;;
    *)
      echo "exit"
      exit 1
      ;;
  esac
fi

# verify virtual environment exists
if ! test -d "${VIRTUAL_ENV}/bin"; then
  echo "Error: directory does not exist: ${VIRTUAL_ENV}/bin"
  exit 1
fi

# write a tmp bashrc file
# use umask to specify initial permissions on tmpfile
umask 0177
tmpfile=$(mktemp "${TMPDIR:-/tmp}"/"${progname}".XXXXXX)
rm -f "${tmpfile}"
touch "${tmpfile}"

# mimic bash interactive shell
if test -f ~/.bashrc; then
  echo "source ~/.bashrc" >>"${tmpfile}"
fi

# activate virtual environment
VIRTUAL_ENV=$(realpath "${VIRTUAL_ENV}")
echo "export VIRTUAL_ENV=\"${VIRTUAL_ENV}\""
echo "export PATH=\"${VIRTUAL_ENV}/bin:\${PATH}\""
echo "export VIRTUAL_ENV=\"${VIRTUAL_ENV}\"" >>"${tmpfile}"
echo "export PATH=\"${VIRTUAL_ENV}/bin:\${PATH}\"" >>"${tmpfile}"

# load .env file if there is one
# set -a causes defined variables to be exported
# shellcheck disable=SC2034
ENV_PATH="${VIRTUAL_ENV}/.env"
# shellcheck disable=SC2129
if test -f "${VIRTUAL_ENV}"; then
  echo "source ${VIRTUAL_ENV}/.env"
  echo "set -a" >>"${tmpfile}"
  echo "source ${VIRTUAL_ENV}/.env" >>"${tmpfile}"
  echo "set +a" >>"${tmpfile}"
fi

# start a subshell initialized with the tmp bashrc we just wrote
# see: https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html
exec bash --rcfile "${tmpfile}"
