#!/usr/bin/env bash
# Compatibility entrypoint for the optional GStack 2 runtime.
# Skill discovery and host placement belong to the Agent Skills installer.
set -euo pipefail
umask 077

SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  SOURCE_DIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
  LINK="$(readlink "$SOURCE")"
  case "$LINK" in
    /*) SOURCE="$LINK" ;;
    *) SOURCE="$SOURCE_DIR/$LINK" ;;
  esac
done
ROOT="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"

# Keep the legacy setup flags harmless during the compatibility window. They
# used to control host-specific skill placement, which now belongs to the
# standard Agent Skills installer; the optional runtime itself is always a
# single per-user local install.
ARGS=()
for arg in "$@"; do
  case "$arg" in
    --local|--team|--no-team)
      echo "gstack setup: $arg is deprecated; skill placement is delegated to: npx skills add time-attack/gstack" >&2
      ;;
    *) ARGS+=("$arg") ;;
  esac
done

NODE_COMMAND="${GSTACK_NODE:-node}"
if ! command -v "$NODE_COMMAND" >/dev/null 2>&1; then
  echo "gstack setup: Node 18+ is required by the managed runtime launchers." >&2
  echo "Install Node from https://nodejs.org, or install judgment-only skills with:" >&2
  echo "  npx skills add time-attack/gstack" >&2
  exit 1
fi

if ! "$NODE_COMMAND" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 18 ? 0 : 1)' >/dev/null 2>&1; then
  echo "gstack setup: Node 18+ is required by the managed runtime launchers." >&2
  exit 1
fi

if ! command -v bun >/dev/null 2>&1; then
  echo "gstack setup: Bun is required to build the optional local runtime." >&2
  echo "Install Bun from https://bun.sh, or install judgment-only skills with:" >&2
  echo "  npx skills add time-attack/gstack" >&2
  exit 1
fi

# Reconcile on every setup. Presence checks cannot distinguish the lockfile's
# exact versions from stale but loadable packages copied from another checkout.
(cd "$ROOT" && bun install --production --frozen-lockfile)

if [ "${#ARGS[@]}" -gt 0 ]; then
  exec "$NODE_COMMAND" "$ROOT/runtime/install.js" --source "$ROOT" "${ARGS[@]}"
else
  exec "$NODE_COMMAND" "$ROOT/runtime/install.js" --source "$ROOT"
fi
