#!/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
    -h|--help)
      printf '%s\n' \
        'Usage: ./setup [--capabilities <list>] [--replace-capabilities] [--dry-run|--install-now [--yes]|--install-later]' \
        '               [--home <path>] [--version <version>] [--json] [--quiet]' \
        '' \
        'Optional capabilities: browser, design, pdf, diagram, ios (iOS is macOS-only).' \
        'Without --install-now, non-interactive use previews and installs nothing.' \
        '--dry-run and --install-later never modify runtime state or host setup.' \
        'Installs only the optional host-neutral runtime and selected local capabilities.' \
        'Skills are installed separately with: npx skills add time-attack/gstack'
      exit 0
      ;;
    --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 [ "${#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
