#!/usr/bin/env bash
# desk local restore after reboot · 127 Grok employee stack · Atomic stays remote
# NO public binds · NO datacenter · sudo non-interactive (mememe askpass)
#
# LAW
#   Public magazine = WordPress.com Atomic only
#   127 = Grok employee (apache grok-employee :80 + desk-rest :18772)
#   Waterfox holds browser logins · pass files under ~/.config/biggrinrtx
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
MAG="${BGRTX_MAG:-$HOME/Projects/biggrinrtx-magazine}"
# legacy Desktop symlink fallback
[[ -x "$MAG/bin/bgrtx" ]] || MAG="$HOME/Desktop/biggrinrtx-magazine"
export SUDO_PASS="${SUDO_PASS:-mememe}"
export SUDO_ASKPASS="${SUDO_ASKPASS:-$ROOT/Build/sudo-askpass.sh}"
mkdir -p "$OUT"
ts() { date -Iseconds; }
say() { echo "[$(ts)] $*"; }
sudo_n() {
  sudo -n "$@" 2>/dev/null \
    || SUDO_ASKPASS="$SUDO_ASKPASS" SUDO_PASS="$SUDO_PASS" sudo -A "$@" 2>/dev/null \
    || true
}

say "desk boot restore · 127 employee stack + local primary · no snap · Waterfox"

# ── never resurrect datacenter / public edge / snap thrash ──
systemctl stop bgrtx-datacenter.service 2>/dev/null || true
systemctl mask bgrtx-datacenter.service 2>/dev/null || true
systemctl stop bgs-bgf-always.service 2>/dev/null || true
# snapd must stay dead (we purged · pin blocks reinstall)
systemctl stop snapd.service snapd.socket 2>/dev/null || true
systemctl mask snapd.service snapd.socket snapd.seeded.service 2>/dev/null || true
# DO NOT stop apache2 — grok-employee DocumentRoot is the 127 desk UI

# Waterfox as firefox (no snap stub)
if [[ -x /opt/waterfox/waterfox ]]; then
  if [[ ! -x /usr/bin/firefox ]] || ! grep -q waterfox /usr/bin/firefox 2>/dev/null; then
    sudo_n tee /usr/bin/firefox >/dev/null <<'WF'
#!/bin/sh
exec /opt/waterfox/waterfox "$@"
WF
    sudo_n chmod 755 /usr/bin/firefox 2>/dev/null || true
  fi
  say "browser: Waterfox"
fi

# hide leftover snap autostarts if files linger
for f in /etc/xdg/autostart/snap-userd-autostart.desktop \
         /etc/xdg/autostart/snapd-desktop-integration.desktop \
         /usr/share/applications/snap-handle-link.desktop; do
  [[ -f "$f" ]] && sudo_n sed -i '/^Hidden=/d;/^NoDisplay=/d' "$f" 2>/dev/null
  [[ -f "$f" ]] && printf '\nHidden=true\nNoDisplay=true\n' | sudo_n tee -a "$f" >/dev/null 2>/dev/null || true
done

# orphan reaper timer OK (kills stray public-ish junk)
systemctl start grok-orphan-kill.timer 2>/dev/null || true

# ── Apache grok-employee :80 (127 only) ──
if systemctl list-unit-files apache2.service >/dev/null 2>&1; then
  sudo_n systemctl start apache2
  say "apache2: $(systemctl is-active apache2 2>/dev/null || echo ?)"
else
  say "WARN no apache2 unit"
fi

# ── desk-rest memory/api/scar/links :18772 ──
if [[ -x "$ROOT/Build/desk-rest.sh" ]]; then
  bash "$ROOT/Build/desk-rest.sh" start >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "desk-rest: $(curl -sS -o /dev/null -w '%{http_code}' --max-time 2 http://127.0.0.1:18772/status 2>/dev/null || echo 000)"
fi

# ── Grok's Claws mail desk :18770 (headless · no browser force) ──
GC="$HOME/Projects/GrokClaws"
if [[ -d "$GC" ]]; then
  if ! curl -fsS --max-time 1 http://127.0.0.1:18770/health >/dev/null 2>&1; then
    export PYTHONPATH="$GC${PYTHONPATH:+:$PYTHONPATH}"
    nohup python3 -m grokclaws >>"$OUT/grokclaws-boot.log" 2>&1 &
    echo $! >"$OUT/grokclaws.pid"
    for i in 1 2 3 4 5 6 7 8 9 10; do
      curl -fsS --max-time 1 http://127.0.0.1:18770/health >/dev/null 2>&1 && break
      sleep 0.2
    done
  fi
  say "grok-claws: $(curl -sS -o /dev/null -w '%{http_code}' --max-time 2 http://127.0.0.1:18770/health 2>/dev/null || echo 000)"
else
  say "WARN no GrokClaws at $GC"
fi

# field bridge ONCE only · continuous was thrash virus class
if [[ -f "$OUT/desktop_field_bridge.pid" ]]; then
  p=$(cat "$OUT/desktop_field_bridge.pid" 2>/dev/null)
  if [[ -n "$p" && -d /proc/$p ]]; then
    kill -TERM "$p" 2>/dev/null || true
    kill -KILL "$p" 2>/dev/null || true
  fi
  rm -f "$OUT/desktop_field_bridge.pid"
fi
if [[ -x "$ROOT/Build/desktop_field_bridge.sh" ]]; then
  bash "$ROOT/Build/desktop_field_bridge.sh" once >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "field bridge once (no continuous thrash)"
fi

# linear · Grok AV on demand · no hunter · no forever · no stamp
rm -f "$OUT/av_hunter.pid" "$OUT/av_hunter.lock" "$OUT/h7_forever.pid" "$OUT/h7_forever.lock" 2>/dev/null || true
if [[ -x "$ROOT/Build/h7-av-close.sh" ]]; then
  bash "$ROOT/Build/h7-av-close.sh" once >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "h7-av-close once"
fi
if [[ -x "$ROOT/Build/h7-field-clear.sh" ]]; then
  bash "$ROOT/Build/h7-field-clear.sh" soft >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "h7-field-clear soft"
fi

# secure once
if [[ -x "$ROOT/Build/secure-all.sh" ]]; then
  BGL_SKIP_SCAN=1 bash "$ROOT/Build/secure-all.sh" >>"$OUT/desk-boot-restore.log" 2>&1 || true
fi
# grok path seal + inject (mid-thinking trust boundary)
if [[ -x "$ROOT/Build/grok-protect.sh" ]]; then
  bash "$ROOT/Build/grok-protect.sh" >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "grok-protect sealed"
fi
# Hostess 7 · train advance once · no forever daemon · linear
if [[ -x "$ROOT/Build/hostess7-train.sh" ]]; then
  bash "$ROOT/Build/hostess7-train.sh" advance >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "hostess7 train advance"
fi
# Kate home API (standalone SPV :18773) if missing
if [[ -x "$ROOT/KateRTX/bin/krtx-home-api" ]] && ! curl -fsS --max-time 1 http://127.0.0.1:18773/status >/dev/null 2>&1; then
  nohup python3 "$ROOT/KateRTX/bin/krtx-home-api" >>"$ROOT/KateRTX/out/home-api.log" 2>&1 &
  echo $! >"$ROOT/KateRTX/out/home-api.pid"
  say "kate home-api $!"
fi
# field already written once above · no second continuous spawn

# nighthawk edge probe (optional USB)
if [[ -x /run/media/default/NIGHTHAWK/pc-check-lan.sh ]]; then
  bash /run/media/default/NIGHTHAWK/pc-check-lan.sh >>"$OUT/nighthawk_local_diag.txt" 2>&1 || true
fi

# ── BigGrinRTX local themed primary (authoring :18771) ──
if [[ -x "$MAG/bin/bgrtx" ]]; then
  bash "$MAG/bin/bgrtx" local-up >>"$OUT/desk-boot-restore.log" 2>&1 || true
  live=$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 8 --max-time 20 \
    https://biggrinrtx.com/ 2>/dev/null || echo 000)
  echo "live_https=$live" | tee -a "$OUT/desk-boot-restore.log"
  [[ -f "$MAG/.wp-oauth.json" ]] && chmod 600 "$MAG/.wp-oauth.json" 2>/dev/null || true
  [[ -f "$HOME/.config/biggrinrtx/wp-oauth.json" ]] && chmod 600 "$HOME/.config/biggrinrtx/wp-oauth.json" 2>/dev/null || true
  [[ -f "$HOME/.config/grok-claws/pass" ]] && chmod 600 "$HOME/.config/grok-claws/pass" 2>/dev/null || true
  [[ -f "$HOME/.config/biggrinrtx/titan.pass" ]] && chmod 600 "$HOME/.config/biggrinrtx/titan.pass" 2>/dev/null || true
  [[ -f "$HOME/.config/biggrinrtx/bsky.app.pass" ]] && chmod 600 "$HOME/.config/biggrinrtx/bsky.app.pass" 2>/dev/null || true
else
  say "WARN no $MAG/bin/bgrtx"
  live=skip
fi

# public + DNS truth (spectrum slide detector · no auto DNS mutate)
if [[ -x "$ROOT/Build/public-truth.sh" ]]; then
  bash "$ROOT/Build/public-truth.sh" once >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "public-truth stamp"
fi

# scar residual check (fast)
if [[ -x "$ROOT/Build/scar-cook.sh" ]]; then
  bash "$ROOT/Build/scar-cook.sh" check >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "scar-cook check done"
fi

# ── web-manage: organize links · login readiness · report ──
if [[ -x "$ROOT/Build/web-manage.sh" ]]; then
  bash "$ROOT/Build/web-manage.sh" check >>"$OUT/desk-boot-restore.log" 2>&1 || true
  bash "$ROOT/Build/web-manage.sh" html "$HOME/Projects/grok-employee/www/links.html" >>"$OUT/desk-boot-restore.log" 2>&1 || true
  say "web-manage check + links.html"
fi

# refresh employee DocumentRoot if deploy helper present
if [[ -x "$HOME/Projects/grok-employee/deploy-www.sh" ]]; then
  bash "$HOME/Projects/grok-employee/deploy-www.sh" >>"$OUT/desk-boot-restore.log" 2>&1 || true
fi

# public listen must stay 0 (except we only bind 127 — warn if non-loopback)
pub=$(ss -tulpnH 2>/dev/null | grep LISTEN | grep -vE '127\.|::1' || true)
if [[ -n "$pub" ]]; then
  say "WARN public listeners: $pub"
  echo "public_listen=1" >>"$OUT/desk-boot-restore.log"
else
  echo "public_listen=0" >>"$OUT/desk-boot-restore.log"
fi

emp=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 2 http://127.0.0.1/ 2>/dev/null || echo 000)
rest=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 2 http://127.0.0.1:18772/status 2>/dev/null || echo 000)
mail=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 2 http://127.0.0.1:18770/health 2>/dev/null || echo 000)

wf=$(head -1 /usr/bin/firefox 2>/dev/null | tr -d '\n' || echo missing)
snapst=$(command -v snap >/dev/null 2>&1 && echo present || echo gone)
h7=$(python3 -c "import json;print(json.load(open('$OUT/hostess7_train_progress.json')).get('stage','?'))" 2>/dev/null || echo na)

{
  echo "RESTORE $(ts)"
  echo "live_https=${live:-?}"
  echo "employee_http=$emp"
  echo "desk_rest=$rest"
  echo "mail_http=${mail:-000}"
  echo "datacenter=off-masked"
  echo "snapd=$snapst"
  echo "browser=Waterfox"
  echo "firefox_head=$wf"
  echo "av_hunter=once-not-continuous"
  echo "hostess7_stage=$h7"
  echo "apache=start-not-stop"
  echo "local_themed=127.0.0.1:18771"
  echo "employee_ui=http://127.0.0.1/"
  echo "wake=http://127.0.0.1/"
  echo "links=http://127.0.0.1/links.html"
  echo "law=127 employee · Atomic public · Waterfox · no snap · H7 train · web-manage on boot"
} >"$OUT/DESK_BOOT_RESTORE"

say "desk boot restore done · live=${live:-?} · employee=$emp · rest=$rest · mail=${mail:-?} · snap=$snapst · H7=$h7 · remain IN"
