#!/usr/bin/env bash
# adom-tsci installer (adom-wiki pkg install / wiki.adom.inc). Pulls the
# prebuilt Linux x86_64 binary from this package's OWN release version —
# the VERSION file ships in the tarball next to this script, and release
# assets live at /download/<owner>/<slug>/<version>/<filename>. There is
# no "latest" download alias on the wiki, and pinning to our own version
# means tarball and binary can never skew.
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
VERSION="$(tr -d '[:space:]' < "$HERE/VERSION")"
BIN_URL="https://wiki.adom.inc/download/adom/adom-tsci/$VERSION/adom-tsci"
DEST="$HOME/.local/bin/adom-tsci"

mkdir -p "$HOME/.local/bin"
echo "→ downloading adom-tsci v$VERSION…"
# Download to a temp file and rename over DEST: writing directly onto a
# RUNNING adom-tsci binary fails with ETXTBSY (curl exit 23); rename(2)
# replaces a busy executable cleanly.
TMP="$DEST.tmp.$$"
trap 'rm -f "$TMP"' EXIT
curl -fsSL "$BIN_URL" -o "$TMP"
chmod +x "$TMP"
mv -f "$TMP" "$DEST"
trap - EXIT
echo "→ installed binary to $DEST ($("$DEST" --version 2>/dev/null || echo '?'))"

# Deploy SKILL.md + guides (adom-tsci ships its own installer for these).
"$DEST" install >/dev/null 2>&1 || echo "  (skill deploy skipped — run 'adom-tsci install' manually if needed)"

case ":$PATH:" in
  *":$HOME/.local/bin:"*) ;;
  *) echo "  NOTE: add ~/.local/bin to PATH: export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
esac
echo "✓ adom-tsci installed. Try: adom-tsci start <project-dir>"