#!/bin/bash
# hx-artex-llm-link: maintain the CAPABLE ARTEX LLM rendezvous endpoint that the HOGSMEADE artexlab VM uses
# (ARTEX LLM profile 2 "Mac qwen3.5:122b", the default; base_url http://10.71.0.1:11436/v1). Package-managed
# replacement for the former hand-run crystalcave:~/.hermes/scripts/hx-artex-beauxbatons-llm.sh.
#
# crystalcave is the hub: the ONLY host that can reach BOTH the beauxbatons (Mac) Ollama and HOGSMEADE. The
# rendezvous address 10.71.0.1:11436 is STABLE and never repointed; this tool only swaps what BACKS it:
#   1. beauxbatons (Mac) qwen3.5:122b-a10b  -- preferred, zero cost, ONLY while the Mac compute gate is open
#      (screen-locked + home LAN + AC power; owner's shared-compute rule). Chain:
#        Mac:127.0.0.1:11434  --ssh -L-->  crystalcave:127.0.0.1:11436  --ssh -R-->  HOGSMEADE:127.0.0.1:11436
#      HOGSMEADE's packaged hogsmeade-artex-capable-bridge then exposes 10.71.0.1:11436 -> 127.0.0.1:11436.
#   2. ephemeral AWS GPU (g5/g6) serving the same/an offensive model -- OFF by default opt-in. The owner rule
#      is "no AWS for personal projects / never propose spending", so this path refuses to launch unless BOTH
#      AWS_GPU_FALLBACK=1 AND the sentinel /etc/ctg-hx-artex-llm/aws-gpu-approved exist. See AWS-GPU.md.
#   3. nothing available -> rendezvous left DOWN; a scan then runs on the weak 9B (profile 1) as last-ditch.
#
# modes:
#   up          bring the best-available capable backend up behind the rendezvous (idempotent, TTL-bounded)
#   down        tear the link (and any ephemeral GPU) down; confirm GPU termination
#   status      report what backs the rendezvous now + a live /api/tags probe from the artexlab VM
#   --supervise run as the systemd service: keep the link up while the gate allows, re-evaluate every INTERVAL
#
# Runs as the agent user (its ~/.ssh/config holds the `beauxbatons` and `hogsmeade-agent` host entries). Never
# changes any Ollama bind off 127.0.0.1 and never touches the Mac beyond a read-only gate probe + an ssh -L.
set -u

CONF=${HXLL_CONF:-/etc/ctg-hx-artex-llm/link.env}
[ -r "$CONF" ] && . "$CONF"
: "${PORT:=11436}" "${MAC_HOST:=beauxbatons}" "${MAC_OLLAMA_PORT:=11434}" "${HOG_HOST:=hogsmeade-agent}"
: "${CAPABLE_MODEL:=qwen3.5:122b-a10b}" "${HOME_GW:=10.66.69.1}" "${TTL:=14400}" "${SUPERVISE_INTERVAL:=120}"
: "${VM_RENDEZVOUS:=10.71.0.1}" "${STATE_DIR:=/run/ctg-hx-artex-llm}"
: "${AWS_GPU_FALLBACK:=0}" "${AWS_PROFILE:=}" "${AWS_REGION:=us-west-2}" "${AWS_GPU_TYPE:=g6.2xlarge}" "${AWS_GPU_AMI:=}"
SSH="ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=30"
if ! mkdir -p "$STATE_DIR" 2>/dev/null || [ ! -w "$STATE_DIR" ]; then
  # on-demand (non-root) use: /run is not writable, fall back to a per-user runtime dir
  STATE_DIR="${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}}/ctg-hx-artex-llm-$(id -u)"
  mkdir -p "$STATE_DIR" 2>/dev/null
fi

log()  { echo "[hx-artex-llm-link] $*"; }
die()  { echo "[hx-artex-llm-link] ERROR: $*" >&2; exit 1; }

# --- beauxbatons compute gate: locked + home LAN + AC power (read-only probe) --------------------------------
mac_gate_ok() {
  local out
  out=$(timeout 20 $SSH -o HostName=${MAC_HOST}.local "$MAC_HOST" \
    'L=$(ioreg -n Root -d1 -a | plutil -extract IOConsoleUsers.0.CGSSessionScreenIsLocked raw - 2>/dev/null); \
     P=$(pmset -g batt 2>/dev/null | grep -o "AC Power"); \
     G=$(route -n get default 2>/dev/null | awk "/gateway/{print \$2}"); \
     echo "lock=$L ac=$P gw=$G"' 2>/dev/null)
  GATE_DETAIL="$out"
  echo "$out" | grep -q 'lock=true' && echo "$out" | grep -q 'ac=AC Power' && echo "$out" | grep -q "gw=${HOME_GW}"
}

mac_serves_model() {
  timeout 15 $SSH -o HostName=${MAC_HOST}.local "$MAC_HOST" \
    "curl -s --max-time 8 http://127.0.0.1:${MAC_OLLAMA_PORT}/api/tags" 2>/dev/null \
    | grep -q "\"${CAPABLE_MODEL}\""
}

# --- tunnel legs (idempotent; TTL-bounded; survive this process) ---------------------------------------------
leg_L_up() { pgrep -f "ssh -N.*-L 127.0.0.1:${PORT}:127.0.0.1:${MAC_OLLAMA_PORT} ${MAC_HOST}" >/dev/null; }
leg_R_up() { pgrep -f "ssh -N.*-R 127.0.0.1:${PORT}:127.0.0.1:${PORT} ${HOG_HOST}" >/dev/null; }

start_leg_L() {
  leg_L_up && return 0
  setsid bash -c "exec timeout $TTL ssh -N -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 \
    -o HostName=${MAC_HOST}.local -L 127.0.0.1:${PORT}:127.0.0.1:${MAC_OLLAMA_PORT} ${MAC_HOST}" >/dev/null 2>&1 &
  sleep 3; leg_L_up
}
start_leg_R() {
  leg_R_up && return 0
  setsid bash -c "exec timeout $TTL ssh -N -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 \
    -R 127.0.0.1:${PORT}:127.0.0.1:${PORT} ${HOG_HOST}" >/dev/null 2>&1 &
  sleep 3; leg_R_up
}
stop_legs() {
  pkill -f "ssh -N.*-L 127.0.0.1:${PORT}:127.0.0.1:${MAC_OLLAMA_PORT} ${MAC_HOST}" 2>/dev/null
  pkill -f "ssh -N.*-R 127.0.0.1:${PORT}:127.0.0.1:${PORT} ${HOG_HOST}" 2>/dev/null
}

# --- verify the rendezvous from inside the artexlab VM -------------------------------------------------------
vm_sees_capable() {
  timeout 30 $SSH "$HOG_HOST" \
    "sudo -n incus exec artexlab -- bash -lc 'curl -s --max-time 8 http://${VM_RENDEZVOUS}:${PORT}/api/tags'" 2>/dev/null \
    | grep -q "\"${CAPABLE_MODEL}\""
}

# --- AWS ephemeral GPU fallback (OFF by default; owner: no AWS for personal projects) ------------------------
aws_fallback_allowed() {
  [ "$AWS_GPU_FALLBACK" = 1 ] && [ -f /etc/ctg-hx-artex-llm/aws-gpu-approved ] && [ -n "$AWS_PROFILE" ]
}
aws_gpu_up() {
  aws_fallback_allowed || { log "AWS GPU fallback disabled (needs AWS_GPU_FALLBACK=1 + /etc/ctg-hx-artex-llm/aws-gpu-approved + AWS_PROFILE)"; return 1; }
  command -v /usr/libexec/hx-artex-aws-gpu >/dev/null 2>&1 || { log "AWS GPU helper not installed"; return 1; }
  /usr/libexec/hx-artex-aws-gpu up "$STATE_DIR" && {
    # the helper writes the instance's reachable Ollama host:port to $STATE_DIR/aws-endpoint
    local ep; ep=$(cat "$STATE_DIR/aws-endpoint" 2>/dev/null)
    [ -n "$ep" ] || return 1
    pgrep -f "ssh -N.*-L 127.0.0.1:${PORT}:${ep} " >/dev/null || \
      setsid bash -c "exec timeout $TTL ssh -N -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 \
        -L 127.0.0.1:${PORT}:${ep} $(cat "$STATE_DIR/aws-ssh-target")" >/dev/null 2>&1 &
    sleep 3; start_leg_R
  }
}
aws_gpu_down() {
  pkill -f "ssh -N.*-L 127.0.0.1:${PORT}:" 2>/dev/null
  [ -x /usr/local/bin/hx-artex-aws-gpu ] && /usr/local/bin/hx-artex-aws-gpu down "$STATE_DIR"
}

do_up() {
  if mac_gate_ok; then
    log "beauxbatons gate OPEN ($GATE_DETAIL)"
    if ! mac_serves_model; then die "Mac is gated-in but does not serve ${CAPABLE_MODEL}"; fi
    start_leg_L || die "ssh -L to the Mac failed"
    start_leg_R || die "ssh -R to HOGSMEADE failed"
    if vm_sees_capable; then
      echo "beauxbatons" > "$STATE_DIR/backend"
      log "UP: rendezvous http://${VM_RENDEZVOUS}:${PORT} backed by beauxbatons ${CAPABLE_MODEL}"
      return 0
    fi
    die "legs up but the artexlab VM cannot see ${CAPABLE_MODEL} on ${VM_RENDEZVOUS}:${PORT} (check hogsmeade-artex-capable-bridge)"
  fi
  log "beauxbatons gate CLOSED ($GATE_DETAIL)"
  if aws_fallback_allowed; then
    log "trying the ephemeral AWS GPU fallback (opt-in enabled)"
    if aws_gpu_up && vm_sees_capable; then
      echo "aws-gpu" > "$STATE_DIR/backend"
      log "UP: rendezvous backed by an ephemeral AWS GPU (will be terminated on 'down')"
      return 0
    fi
    aws_gpu_down
    die "AWS GPU fallback did not come up; rendezvous left down (scan will use the 9B last-ditch)"
  fi
  rm -f "$STATE_DIR/backend"
  stop_legs
  log "No capable backend available; rendezvous DOWN. A scan will fall back to the 9B (profile 1)."
  return 2
}

do_down() {
  stop_legs
  aws_gpu_down
  rm -f "$STATE_DIR/backend"
  log "link down; any ephemeral GPU terminated (confirm with: hx-artex-aws-gpu confirm)"
}

do_status() {
  local b tags
  b=$(cat "$STATE_DIR/backend" 2>/dev/null || echo none)
  echo "backend:     $b"
  echo "leg Mac(-L): $(leg_L_up && echo up || echo down)"
  echo "leg HOG(-R): $(leg_R_up && echo up || echo down)"
  tags=$(timeout 30 $SSH "$HOG_HOST" \
    "sudo -n incus exec artexlab -- bash -lc 'curl -s --max-time 8 http://${VM_RENDEZVOUS}:${PORT}/api/tags'" 2>/dev/null)
  if echo "$tags" | grep -q "\"${CAPABLE_MODEL}\""; then
    echo "rendezvous:  http://${VM_RENDEZVOUS}:${PORT}  serving ${CAPABLE_MODEL}  (capable - profile 2)"
  else
    echo "rendezvous:  http://${VM_RENDEZVOUS}:${PORT}  NOT serving ${CAPABLE_MODEL}  (scans should pin profile 1 / 9b)"
  fi
}

supervise() {
  log "supervise loop (interval ${SUPERVISE_INTERVAL}s, leg TTL ${TTL}s)"
  while :; do
    do_up || true
    sleep "$SUPERVISE_INTERVAL"
  done
}

case "${1:-status}" in
  up)         do_up ;;
  down)       do_down ;;
  status)     do_status ;;
  --supervise) supervise ;;
  *) echo "usage: hx-artex-llm-link up|down|status|--supervise" >&2; exit 2 ;;
esac
