#!/usr/bin/env bash
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# Installs the `experiments` command from this checkout, the way `aws/install` installs the AWS CLI:
#
#   git clone <this repository>
#   <checkout>/install
#
# The command gets its own Python environment under the install directory, so nothing is installed
# into the system or user Python and no pip or venv step is left to the user. Running it again
# (after `git pull`) replaces the install; the previous one keeps working until the new one is
# ready. Needs Python 3.10 or newer somewhere on the machine (it looks on PATH and in mise, uv,
# pyenv and Homebrew installs), or uv to fetch one.
#
#   ./install [--install-dir DIR] [--bin-dir DIR] [--python PATH]
#   ./install --uninstall [--install-dir DIR] [--bin-dir DIR]

set -euo pipefail

REPO="$(cd "$(dirname "$0")" && pwd -P)"
INSTALL_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/omni-experiments"
BIN_DIR="$HOME/.local/bin"
PYTHON="${PYTHON:-}"
UNINSTALL=0
MARKER=".omni-experiments-install"

usage() {
    sed -n '5,17p' "$0" | sed 's/^# \{0,1\}//'
    cat <<EOF

Options:
  --install-dir DIR  where the command's Python environment goes (default: $INSTALL_DIR)
  --bin-dir DIR      where the \`experiments\` link goes (default: $BIN_DIR)
  --python PATH      the Python 3.10+ interpreter to build it with (default: found automatically)
  --uninstall        remove the install and the link
EOF
}

die() { echo "install: $*" >&2; exit 1; }

while [ $# -gt 0 ]; do
    case "$1" in
        --install-dir) [ $# -ge 2 ] || die "--install-dir needs a value"; INSTALL_DIR="$2"; shift 2 ;;
        --bin-dir) [ $# -ge 2 ] || die "--bin-dir needs a value"; BIN_DIR="$2"; shift 2 ;;
        --python) [ $# -ge 2 ] || die "--python needs a value"; PYTHON="$2"; shift 2 ;;
        --uninstall) UNINSTALL=1; shift ;;
        -h|--help) usage; exit 0 ;;
        *) usage >&2; exit 2 ;;
    esac
done

case "$INSTALL_DIR" in /*) ;; *) INSTALL_DIR="$PWD/$INSTALL_DIR" ;; esac
case "$BIN_DIR" in /*) ;; *) BIN_DIR="$PWD/$BIN_DIR" ;; esac
LINK="$BIN_DIR/experiments"

# True when $LINK is a symlink this script made (it points into the install directory).
our_link() {
    [ -L "$LINK" ] || return 1
    case "$(readlink "$LINK")" in "$INSTALL_DIR"/*) return 0 ;; *) return 1 ;; esac
}

if [ "$UNINSTALL" = 1 ]; then
    if our_link; then rm -f "$LINK"; echo "removed $LINK"; fi
    if [ -f "$INSTALL_DIR/$MARKER" ]; then
        rm -rf "$INSTALL_DIR"
        echo "removed $INSTALL_DIR"
    elif [ -e "$INSTALL_DIR" ]; then
        die "$INSTALL_DIR wasn't made by this script; not removing it"
    fi
    exit 0
fi

[ -f "$REPO/pyproject.toml" ] && [ -d "$REPO/src/omni_experiments" ] \
    || die "run this from a checkout of the repository ($REPO isn't one)"

# A usable interpreter: Python 3.10 or newer that can make a virtual environment with pip.
usable() {
    [ -n "$1" ] && [ -x "$1" ] || command -v "$1" >/dev/null 2>&1 || return 1
    "$1" -c 'import sys, venv, ensurepip; sys.exit(sys.version_info < (3, 10))' >/dev/null 2>&1
}

find_python() {
    local c
    for c in python3.13 python3.12 python3.11 python3.10 python3; do
        if usable "$c"; then command -v "$c"; return 0; fi
    done
    for c in \
        "${MISE_DATA_DIR:-$HOME/.local/share/mise}"/installs/python/3.1[0-3]*/bin/python3 \
        "${UV_PYTHON_INSTALL_DIR:-$HOME/.local/share/uv/python}"/cpython-3.1[0-3]*/bin/python3 \
        "${PYENV_ROOT:-$HOME/.pyenv}"/versions/3.1[0-3]*/bin/python3 \
        /opt/homebrew/bin/python3.1[0-3] /usr/local/bin/python3.1[0-3]; do
        if usable "$c"; then echo "$c"; return 0; fi
    done
    if command -v uv >/dev/null 2>&1; then
        echo "install: no Python 3.10+ found; fetching Python 3.12 with uv" >&2
        uv python install 3.12 >&2 && c="$(uv python find 3.12)" && usable "$c" && { echo "$c"; return 0; }
    fi
    return 1
}

if [ -n "$PYTHON" ]; then
    usable "$PYTHON" || die "$PYTHON isn't Python 3.10+ with venv and ensurepip"
    PYTHON="$(command -v "$PYTHON")"
else
    PYTHON="$(find_python)" || die "needs Python 3.10 or newer, and none was found.
  Get one, then run ./install again (or pass --python PATH):
    mise use -g python@3.12           # with mise
    uv python install 3.12            # with uv
    brew install python@3.12          # macOS with Homebrew"
fi

if [ -e "$LINK" ] && ! our_link; then
    die "$LINK already exists and isn't from this script; move it, or pass --bin-dir"
fi
if [ -e "$INSTALL_DIR" ] && [ ! -f "$INSTALL_DIR/$MARKER" ]; then
    die "$INSTALL_DIR exists and wasn't made by this script; pass --install-dir"
fi

echo "Python: $PYTHON ($("$PYTHON" -c 'import platform; print(platform.python_version())'))"
mkdir -p "$INSTALL_DIR" "$BIN_DIR"
touch "$INSTALL_DIR/$MARKER"

# Each install gets a fresh environment beside the current one; `current` switches to it only once
# it works, so a failed install leaves the previous one in place. (A venv can't be moved after it is
# made: its scripts name its absolute path.)
ENV_DIR="$INSTALL_DIR/env-$(date +%Y%m%d%H%M%S)-$$"
cleanup() { if [ -n "${ENV_DIR:-}" ]; then rm -rf "$ENV_DIR"; fi; }
trap cleanup EXIT

echo "Building the environment in $ENV_DIR"
"$PYTHON" -m venv "$ENV_DIR"
"$ENV_DIR/bin/python" -m pip install --quiet --disable-pip-version-check --upgrade pip
"$ENV_DIR/bin/python" -m pip install --quiet --disable-pip-version-check "$REPO"
VERSION="$("$ENV_DIR/bin/experiments" --version)" || die "the new install doesn't run"

# -n replaces the old `current` link itself instead of following it into the old environment.
ln -sfn "$ENV_DIR" "$INSTALL_DIR/current"
ln -sfn "$INSTALL_DIR/current/bin/experiments" "$LINK"
KEEP="$ENV_DIR"
ENV_DIR=""
for old in "$INSTALL_DIR"/env-*; do
    [ "$old" = "$KEEP" ] || rm -rf "$old"
done

echo "Installed $VERSION: $LINK"
case ":$PATH:" in
    *":$BIN_DIR:"*) ;;
    *) echo
       echo "$BIN_DIR isn't on your PATH. Add this to your shell profile (~/.zshrc or ~/.bashrc):"
       echo "  export PATH=\"$BIN_DIR:\$PATH\"" ;;
esac
