#!/bin/bash
set -e

BOOTSTRAP_SLUG="${1:-adom/core}"
REGISTRY="${ADOM_WIKI_REGISTRY:-https://wiki.adom.inc}"
BIN_DIR="$HOME/.local/bin"

# The registry this script downloads the adom-wiki CLI from is the root of trust:
# whoever serves the CLI controls every later "verified" install. Refuse a
# plaintext (downgradable/MITM-able) or non-Adom registry so a hijacked
# ADOM_WIKI_REGISTRY can't deliver a backdoored CLI. localhost is allowed over
# http for dev; ADOM_WIKI_ALLOW_INSECURE_REGISTRY=1 is an explicit opt-out.
reg_scheme="${REGISTRY%%://*}"
reg_rest="${REGISTRY#*://}"
reg_host="${reg_rest%%/*}"   # strip path
reg_host="${reg_host##*@}"   # strip any userinfo (https://trusted@evil.com)
reg_host="${reg_host%%:*}"   # strip :port
reg_is_local=0
case "$reg_host" in
  localhost|127.0.0.1|::1) reg_is_local=1 ;;
esac
# Dead/decommissioned mirrors: still answer + match *.adom.cloud, but serve a
# stale registry and silently downgrade installs. Refuse outright and point at live.
case "$reg_host" in
  git-wiki-ktqxite5iglh.adom.cloud|wiki-ufypy5dpx93o.adom.cloud)
    echo "ERROR: '$reg_host' is a DEAD registry mirror (stale copy; publishes go nowhere, installs get downgraded)." >&2
    echo "       Use the live registry: ADOM_WIKI_REGISTRY=https://wiki.adom.inc (or unset it)." >&2
    exit 1 ;;
esac
reg_trusted=0
case "$reg_host" in
  adom.inc|*.adom.inc|adom.cloud|*.adom.cloud) reg_trusted=1 ;;
esac
if [ "${ADOM_WIKI_ALLOW_INSECURE_REGISTRY:-0}" != "1" ] && [ "$reg_is_local" != "1" ]; then
  if [ "$reg_scheme" != "https" ]; then
    echo "ERROR: refusing to fetch adom-wiki over insecure '$reg_scheme://' from '$reg_host'." >&2
    echo "       The CLI is the root of trust; use https, or set ADOM_WIKI_ALLOW_INSECURE_REGISTRY=1 to override." >&2
    exit 1
  fi
  if [ "$reg_trusted" != "1" ]; then
    echo "ERROR: refusing to fetch adom-wiki from untrusted registry host '$reg_host'." >&2
    echo "       Set ADOM_WIKI_ALLOW_INSECURE_REGISTRY=1 to override (you are trusting that host with code execution)." >&2
    exit 1
  fi
fi

echo "Installing adom-wiki from $REGISTRY..."

mkdir -p "$BIN_DIR"

# adom-wiki is a single self-contained binary. Resolve the latest published release
# of adom/adom-wiki-cli from the registry (no CLI yet, so curl + python3) and fetch
# its linux asset. This always pulls the current release (no stale static mirror).
command -v python3 >/dev/null 2>&1 || { echo "ERROR: python3 is required to bootstrap adom-wiki." >&2; exit 1; }
AWVER="$(curl -fsSL "$REGISTRY/api/packages/adom/adom-wiki-cli/dist-tags" \
  | python3 -c 'import sys,json;print(json.load(sys.stdin).get("dist_tags",{}).get("latest",""))' 2>/dev/null)"
[ -n "$AWVER" ] || { echo "ERROR: could not resolve the latest adom-wiki version from $REGISTRY." >&2; exit 1; }
# Resolve the binary for THIS (os, arch). Tiers 1-3 mirror the server's
# resolveAsset exactly: exact (platform,arch) -> (platform, universal/any) ->
# platform=any. Tier 4 is a bootstrap-only safety net: if none match (e.g. an
# unrecognized uname -m), fall back to any same-platform binary so the container
# always installs. Assets with no arch key default to "any" (wildcard), so this
# is safe with today's assets and pre-1.0.14 releases.
case "$(uname -s)" in Linux) P=linux;; Darwin) P=macos;; *) P=any;; esac
case "$(uname -m)" in x86_64|amd64) A=x64;; aarch64|arm64) A=arm64;; *) A=any;; esac
AWURL="$(curl -fsSL "$REGISTRY/api/packages/adom/adom-wiki-cli/$AWVER/assets" \
  | P="$P" A="$A" python3 -c 'import sys,json,os
P=os.environ["P"]; A=os.environ["A"]
a=json.load(sys.stdin).get("assets",[])
def ax(x): return x.get("arch","any")
m=(next((x for x in a if x.get("platform")==P and ax(x)==A), None)
   or next((x for x in a if x.get("platform")==P and ax(x) in ("universal","any")), None)
   or next((x for x in a if x.get("platform")=="any"), None)
   or next((x for x in a if x.get("platform")==P), None))
print(m["download_url"] if m else "")' 2>/dev/null)"
[ -n "$AWURL" ] || { echo "ERROR: no adom-wiki release asset for $AWVER ($P/$A)." >&2; exit 1; }
case "$AWURL" in http*) : ;; *) AWURL="$REGISTRY$AWURL" ;; esac
curl -fsSL "$AWURL" -o "$BIN_DIR/adom-wiki"
chmod +x "$BIN_DIR/adom-wiki"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) export PATH="$BIN_DIR:$PATH" ;;
esac

add_path_line() {
  local rc="$1"
  [ -f "$rc" ] || return 0
  if ! grep -q 'PATH="$HOME/.local/bin:$PATH"' "$rc" 2>/dev/null; then
    echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$rc"
    echo "  appended PATH to $rc"
  else
    echo "  PATH already in $rc"
  fi
}

add_path_line "$HOME/.bashrc"
[ -f "$HOME/.zshrc" ] && add_path_line "$HOME/.zshrc"

echo "Verifying install..."
adom-wiki --version

echo ""
echo "Installing bootstrap package: $BOOTSTRAP_SLUG ..."
# Never let a single package abort the whole bootstrap (set -e is on). adom-wiki
# skips needs_sudo packages with a note and exits 0; the guard also covers a genuine
# single-package failure so the completion below still runs.
#
# RETRY, because this call races prod DEPLOYS: the registry restarts several
# times on a busy day, and a resolve during the ~10-30s swap window fails. This
# line used to swallow that with a one-line warning and print "Bootstrap
# complete" -- leaving a container with the CLI but ZERO skills, and (worse) no
# auto-update hook, since the hook is itself a core dep: the one failure mode
# the fleet cannot self-heal from. Three attempts spanning ~50s outlast a swap.
install_ok=0
for attempt in 1 2 3; do
  if adom-wiki pkg install "$BOOTSTRAP_SLUG"; then install_ok=1; break; fi
  if [ "$attempt" -lt 3 ]; then
    wait_s=$((attempt * 15))
    echo "  install attempt $attempt failed (registry deploying?); retrying in ${wait_s}s..."
    sleep "$wait_s"
  fi
done
if [ "$install_ok" -ne 1 ]; then
  echo ""
  echo "  ############################################################"
  echo "  ##  BOOTSTRAP INCOMPLETE: '$BOOTSTRAP_SLUG' did not install."
  echo "  ##  The CLI works, but skills/apps and the auto-update hook"
  echo "  ##  are MISSING and this container will NOT self-heal."
  echo "  ##  Fix (one command, rerun until it succeeds):"
  echo "  ##      adom-wiki pkg install $BOOTSTRAP_SLUG"
  echo "  ############################################################"
  echo ""
  mkdir -p "$HOME/.adom" 2>/dev/null || true
  echo "$BOOTSTRAP_SLUG" > "$HOME/.adom/bootstrap-incomplete" 2>/dev/null || true
  # Docker image builds MUST fail rather than bake a half-provisioned layer
  # (the July 2026 vscode image baked "CLI + no skills + no hook" this way and
  # mass-produced unhealable containers). Set ADOM_BOOTSTRAP_STRICT=1 in any
  # RUN that pipes this script; interactive runs keep the lenient default.
  if [ -n "${ADOM_BOOTSTRAP_STRICT:-}" ]; then
    echo "ERROR: ADOM_BOOTSTRAP_STRICT is set; failing the bootstrap." >&2
    exit 1
  fi
fi

# Update mechanism: adom/core depends on adom/hook, whose install.sh (run by the
# install above) wires a registry-native, cross-agent auto-update hook into Claude
# (~/.claude/settings.json) AND Codex (~/.codex/hooks.json). It checks the registry
# on every prompt (throttled ~30m) and applies updates in the background. Retire any
# legacy ~/.bashrc shell nudge from an earlier bootstrap, surgically.
if [ -f "$HOME/.bashrc" ] && grep -q 'check-updates.sh' "$HOME/.bashrc" 2>/dev/null; then
  if grep -v 'check-updates.sh' "$HOME/.bashrc" > "$HOME/.bashrc.adomtmp" 2>/dev/null; then
    mv "$HOME/.bashrc.adomtmp" "$HOME/.bashrc"
    echo "  retired the legacy ~/.bashrc update nudge (the cross-agent hook replaces it)"
  else
    rm -f "$HOME/.bashrc.adomtmp"
  fi
fi
if adom-wiki pkg list 2>/dev/null | grep -q 'adom/hook'; then
  echo "  cross-agent auto-update hook active (adom/hook)"
fi

echo ""
echo "================================================================"
echo "  Bootstrap complete"
echo "================================================================"
echo ""
# `adom-wiki pkg list` prints a JSON {count, packages[]} envelope, so read the
# count out of it (a line-count miscounted it; dumping the raw JSON was noise).
INSTALLED_COUNT=$(adom-wiki pkg list 2>/dev/null | python3 -c 'import sys,json
try: print(json.load(sys.stdin).get("count",0))
except Exception: print(0)' 2>/dev/null)
echo "  ${INSTALLED_COUNT:-0} package(s) installed.  (run: adom-wiki pkg list)"
echo ""
# The script appended ~/.local/bin to ~/.bashrc, but THIS shell hasn't reloaded
# it, so `adom-wiki` isn't on PATH in the caller's session yet.
echo "  Run: source ~/.bashrc   (or open a new shell) to use adom-wiki."
echo "  Wiki: https://wiki.adom.inc"
echo ""
