#!/bin/sh
# Interlock CLI installer - POSIX sh, no bashisms, because the site prints
#   curl -fsSL https://interlock-a05.pages.dev/install.sh | sh -s -- --yes
#
# What it does, in order, and nothing else:
#   1. checks Node >= 22.6 and git are on PATH, and names the missing one if not
#   2. asks for confirmation unless --yes (a piped stdin cannot answer, so pass --yes)
#   3. downloads <base>/cli/interlock-cli-<version>.tgz (an `npm pack` of the package)
#   4. extracts it to <prefix>/lib and writes a shim at <prefix>/bin/interlock
#   5. runs `interlock doctor --json` and prints the result, so success is proved not assumed
#
# It writes NOTHING outside <prefix>. It does not edit your shell profile or PATH; it tells
# you the line to add. No telemetry, no phone-home: one GET for the tarball and that is all.
#
# Flags:   --yes            non-interactive
#          --prefix <dir>   install root (default $INTERLOCK_PREFIX or $HOME/.interlock)
#          --help
# Env:     INTERLOCK_BASE_URL   site root (default https://interlock-a05.pages.dev); for local testing
#          INTERLOCK_PREFIX     same as --prefix
#
# VERIFIED BY EXECUTION on Windows 11 under Git Bash (sh) only. macOS and Linux are NOT
# verified: there is no CI. See install/README.md.

set -eu

VERSION="0.1.0"
BASE_URL="${INTERLOCK_BASE_URL:-https://interlock-a05.pages.dev}"
PREFIX="${INTERLOCK_PREFIX:-$HOME/.interlock}"
YES=0

usage() {
  echo "usage: install.sh [--yes] [--prefix <dir>]"
  echo "  installs interlock-cli $VERSION from $BASE_URL to <prefix> (default $HOME/.interlock)"
}

while [ $# -gt 0 ]; do
  case "$1" in
    --yes|-y) YES=1 ;;
    --prefix) shift; [ $# -gt 0 ] || { echo "install.sh: --prefix needs a directory" >&2; exit 2; }; PREFIX="$1" ;;
    --prefix=*) PREFIX="${1#--prefix=}" ;;
    --help|-h) usage; exit 0 ;;
    *) echo "install.sh: unknown flag: $1" >&2; usage >&2; exit 2 ;;
  esac
  shift
done

fail() { echo "" >&2; echo "install.sh: $1" >&2; echo "" >&2; exit 1; }

# --- 1. prerequisites: Node >= 22.6 and git ------------------------------------------------
if ! command -v node >/dev/null 2>&1; then
  fail "Node.js is not on PATH. Interlock needs Node >= 22.6 - https://nodejs.org - then run this again."
fi
NODE_V="$(node -v 2>/dev/null | sed 's/^v//')"
NODE_MAJ="${NODE_V%%.*}"
NODE_REST="${NODE_V#*.}"
NODE_MIN="${NODE_REST%%.*}"
case "$NODE_MAJ" in ''|*[!0-9]*) fail "could not read the Node version from 'node -v' (got '$NODE_V')" ;; esac
if [ "$NODE_MAJ" -lt 22 ] || { [ "$NODE_MAJ" -eq 22 ] && [ "$NODE_MIN" -lt 6 ]; }; then
  fail "Node v$NODE_V is too old. Interlock needs Node >= 22.6 (Node 20 LTS is not enough). Upgrade at https://nodejs.org and run this again."
fi
if ! command -v git >/dev/null 2>&1; then
  fail "git is not on PATH. Interlock needs git - https://git-scm.com - then run this again."
fi

# --- a downloader ---------------------------------------------------------------------------
if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -q "$1" -O "$2"; }
else
  fail "neither curl nor wget is on PATH; one of them is needed to download the package."
fi
command -v tar >/dev/null 2>&1 || fail "tar is not on PATH; it is needed to unpack the package."

TGZ_URL="$BASE_URL/cli/interlock-cli-$VERSION.tgz"

echo ""
echo "  interlock-cli $VERSION"
echo "  node   v$NODE_V   ok"
echo "  git    $(git --version)"
echo "  from   $TGZ_URL"
echo "  to     $PREFIX"
echo ""

# --- 2. confirmation -------------------------------------------------------------------------
if [ "$YES" -ne 1 ]; then
  printf "  Proceed? [y/N] "
  if ! read -r ANSWER 2>/dev/null </dev/tty; then
    echo ""
    fail "no terminal to ask on. Re-run with --yes:  curl -fsSL $BASE_URL/install.sh | sh -s -- --yes"
  fi
  case "$ANSWER" in y|Y|yes|YES) ;; *) echo "  aborted."; exit 1 ;; esac
fi

# --- 3. download ----------------------------------------------------------------------------
mkdir -p "$PREFIX/bin" "$PREFIX/lib" "$PREFIX/tmp"
PREFIX="$(cd "$PREFIX" && pwd)"
TGZ="$PREFIX/tmp/interlock-cli-$VERSION.tgz"
fetch "$TGZ_URL" "$TGZ" || fail "download failed: $TGZ_URL"
[ -s "$TGZ" ] || fail "download produced an empty file: $TGZ_URL"

# --- 4. extract + shim ------------------------------------------------------------------------
# `npm pack` puts everything under a top-level package/ - strip it so lib/ holds bin/ and src/.
rm -rf "$PREFIX/lib"
mkdir -p "$PREFIX/lib"
tar -xzf "$TGZ" -C "$PREFIX/lib" --strip-components=1 || fail "could not unpack $TGZ"
rm -f "$TGZ"
rmdir "$PREFIX/tmp" 2>/dev/null || true
[ -f "$PREFIX/lib/bin/interlock.mjs" ] || fail "the package did not contain bin/interlock.mjs - wrong tarball at $TGZ_URL?"

cat > "$PREFIX/bin/interlock" <<EOF
#!/bin/sh
# interlock-cli $VERSION shim, written by install.sh. Delete $PREFIX to uninstall.
exec node "$PREFIX/lib/bin/interlock.mjs" "\$@"
EOF
chmod +x "$PREFIX/bin/interlock"

# Under Git Bash / MSYS on Windows, cmd.exe and PowerShell need a .cmd next to it.
case "$(uname -s 2>/dev/null)" in
  MINGW*|MSYS*|CYGWIN*)
    WIN_PREFIX="$(cd "$PREFIX" && { pwd -W 2>/dev/null || pwd; } | tr '/' '\\\\')"
    printf '@echo off\r\nnode "%%~dp0..\\lib\\bin\\interlock.mjs" %%*\r\n' > "$PREFIX/bin/interlock.cmd"
    ;;
  *) WIN_PREFIX="" ;;
esac

# --- 5. prove it ------------------------------------------------------------------------------
echo "  installed to $PREFIX"
echo ""
echo "  self-check:"
DOCTOR="$(node "$PREFIX/lib/bin/interlock.mjs" doctor --json)" || fail "the installed CLI failed its self-check: $DOCTOR"
echo "  $DOCTOR"
echo ""
echo "  Add it to your PATH (this script does not edit your shell profile):"
echo "    export PATH=\"$PREFIX/bin:\$PATH\""
[ -n "$WIN_PREFIX" ] && echo "    (Windows: $WIN_PREFIX\\bin)"
echo ""
echo "  Then:  interlock check tasks.md"
echo ""
