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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VENV_DIR="$ROOT_DIR/.venv"
PYTHON_BIN="${PYTHON_BIN:-python3}"
VIRTUALENV_BIN="${VIRTUALENV_BIN:-$HOME/.local/bin/virtualenv}"

ensure_user_pip() {
  if "$PYTHON_BIN" -m pip --version >/dev/null 2>&1; then
    return 0
  fi

  mkdir -p /tmp/jobtracker-python-bootstrap
  cd /tmp/jobtracker-python-bootstrap
  if [[ ! -f get-pip.py ]]; then
    curl -fsSLo get-pip.py https://bootstrap.pypa.io/get-pip.py
  fi
  "$PYTHON_BIN" get-pip.py --user --break-system-packages
}

ensure_venv() {
  if [[ -x "$VENV_DIR/bin/python" && -x "$VENV_DIR/bin/pip" ]]; then
    return 0
  fi

  if "$PYTHON_BIN" -m venv "$VENV_DIR" >/dev/null 2>&1; then
    return 0
  fi

  ensure_user_pip
  if [[ ! -x "$VIRTUALENV_BIN" ]]; then
    "$PYTHON_BIN" -m pip install --user --break-system-packages virtualenv
  fi
  "$VIRTUALENV_BIN" "$VENV_DIR"
}

install_requirements() {
  "$VENV_DIR/bin/pip" install -r "$ROOT_DIR/requirements-dev.txt"
}

run_tests() {
  mkdir -p "$ROOT_DIR/tmp/pytest-cache"
  cd "$ROOT_DIR"
  AI_SERVICE_SKIP_MODEL_LOAD=1 "$VENV_DIR/bin/python" -m pytest -q -o cache_dir=tmp/pytest-cache tests/test_app.py
}

case "${1:-test}" in
  bootstrap)
    ensure_venv
    install_requirements
    ;;
  test)
    ensure_venv
    install_requirements
    run_tests
    ;;
  *)
    echo "Usage: $0 [bootstrap|test]" >&2
    exit 2
    ;;
esac
