#!/bin/sh
# Loomtide installer + updater — ONE command for install AND update.
#
#   curl -fsSL https://get.loomtide.ai | sh
#   curl -fsSL https://get.loomtide.ai | sh -s -- --project /path/to/UnityProject
#
# Re-run any time to pull the latest release — this script is idempotent, so the
# same command installs on a fresh machine and updates on an existing one.
#
# The Loomtide repo is PRIVATE, so fetching the release asset needs auth. Either:
#   - log in once with the GitHub CLI:  gh auth login        (recommended)
#   - or export a GitHub token:         LOOMTIDE_TOKEN=<pat>  (CI / no gh CLI)
# Your developers already have GitHub accounts — no npm account is required.
#
# Env overrides:
#   LOOMTIDE_VERSION   pin a release tag (default: latest)
#   LOOMTIDE_REPO      source repo (default: AtlasAIEngine/Loomtide)
#   LOOMTIDE_TOKEN     GitHub token with read access (CI / no gh CLI)
#   LOOMTIDE_PROJECT   Unity project to also install/update the bridge into
set -eu

REPO="${LOOMTIDE_REPO:-AtlasAIEngine/Loomtide}"
VERSION="${LOOMTIDE_VERSION:-latest}"
PROJECT="${LOOMTIDE_PROJECT:-}"
ASSET_GLOB='loomtide-cli-*.tgz'

usage() {
  sed -n '2,25p' "$0" 2>/dev/null | sed 's/^# \{0,1\}//'
}

while [ $# -gt 0 ]; do
  case "$1" in
    --project) PROJECT="${2:-}"; shift 2 ;;
    --version) VERSION="${2:-}"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "loomtide install: unknown argument '$1'" >&2; exit 2 ;;
  esac
done

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

command -v node >/dev/null 2>&1 || err "Node.js >= 18 is required (not found)."
command -v npm  >/dev/null 2>&1 || err "npm is required (not found)."

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
tgz=""

echo "==> Fetching Loomtide CLI ($VERSION) from $REPO"
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
  # GitHub CLI path — uses the developer's existing `gh auth login`.
  if [ "$VERSION" = latest ]; then
    gh release download -R "$REPO" -p "$ASSET_GLOB" -D "$tmp" \
      || err "could not download the latest release (check your repo access)."
  else
    gh release download "$VERSION" -R "$REPO" -p "$ASSET_GLOB" -D "$tmp" \
      || err "could not download release $VERSION (check the tag and your access)."
  fi
  tgz="$(ls "$tmp"/loomtide-cli-*.tgz 2>/dev/null | head -1 || true)"
elif [ -n "${LOOMTIDE_TOKEN:-}" ]; then
  # Token path — CI or machines without the gh CLI. Needs curl.
  command -v curl >/dev/null 2>&1 || err "curl is required for the LOOMTIDE_TOKEN path."
  if [ "$VERSION" = latest ]; then
    rel="https://api.github.com/repos/$REPO/releases/latest"
  else
    rel="https://api.github.com/repos/$REPO/releases/tags/$VERSION"
  fi
  meta="$(curl -fsSL -H "Authorization: Bearer $LOOMTIDE_TOKEN" \
                     -H "Accept: application/vnd.github+json" "$rel")" \
    || err "could not read release metadata (check LOOMTIDE_TOKEN / repo access)."
  # Resolve the asset's API URL with node (a hard dependency anyway — no jq needed).
  asset_url="$(printf '%s' "$meta" | node -e '
    let s = ""; process.stdin.on("data", (d) => (s += d)).on("end", () => {
      const rel = JSON.parse(s);
      const a = (rel.assets || []).find((a) => /^loomtide-cli-.*\.tgz$/.test(a.name));
      if (!a) process.exit(3);
      process.stdout.write(a.url);
    });')" || err "no $ASSET_GLOB asset found in release $VERSION."
  curl -fsSL -H "Authorization: Bearer $LOOMTIDE_TOKEN" -H "Accept: application/octet-stream" \
       -o "$tmp/cli.tgz" "$asset_url" || err "release asset download failed."
  tgz="$tmp/cli.tgz"
else
  err "no auth available. Run 'gh auth login' (GitHub CLI) or set LOOMTIDE_TOKEN=<github token>."
fi

[ -n "$tgz" ] && [ -f "$tgz" ] || err "release asset $ASSET_GLOB was not found."

echo "==> Installing globally: npm install -g $(basename "$tgz")"
npm install -g "$tgz" || err "'npm install -g' failed (is your npm global bin writable / on PATH?)."

if command -v loomtide >/dev/null 2>&1; then
  echo "==> Installed: $(loomtide --version 2>/dev/null || echo loomtide)"
else
  echo "!!  Installed, but 'loomtide' is not on your PATH."
  echo "    Add your npm global bin to PATH:  export PATH=\"\$(npm prefix -g)/bin:\$PATH\""
fi

if [ -n "$PROJECT" ]; then
  echo "==> Installing/updating the Unity bridge into $PROJECT"
  loomtide install-bridge --project "$PROJECT"
fi

echo "==> Done. Re-run this exact command any time to update."
