#!/usr/bin/env bash
# desk-clean · field hygiene cleaning interface for desk services
# NOT antivirus · NOT xdg-open (xdg-open = virus / desk ban)
# Law: BGS ground · BGF measure · free SPV ride · never fold
set -euo pipefail

XROOT="${XROOT:-/home/default/Projects/x}"
OUT="$XROOT/out"
JSON="$OUT/bgf_reinstant.json"
ORPHAN_LOG="${GROK_ORPHAN_LOG:-/home/default/.local/state/grok-orphan-kill.log}"
c="${1:-ui}"

# never launch browsers via xdg — print URL only
print_url() { echo "URL (type into browser · NEVER xdg-open): $1"; }

bar() {
  local n=${1:-40}
  printf '%*s\n' "$n" '' | tr ' ' '─'
}

status_unit() {
  local u=$1
  local a e
  a=$(systemctl is-active "$u" 2>/dev/null || echo dead)
  e=$(systemctl is-enabled "$u" 2>/dev/null || echo unknown)
  printf '  %-28s active=%-10s enabled=%s\n' "$u" "$a" "$e"
}

cmd_ui() {
  clear 2>/dev/null || true
  cat <<'HDR'
╔══════════════════════════════════════════════════════════════════╗
║  BGRTX · FIELD HYGIENE CLEANING INTERFACE                        ║
║  services · BGF reinstant · orphan reaper · xdg = virus          ║
║  NOT commercial antivirus · measure / clean / thrash only        ║
╚══════════════════════════════════════════════════════════════════╝
HDR
  echo
  echo "LAW  BGS → BGF → SDF → SPV free · free thrift · remain IN"
  echo "BAN  xdg-open · xdg-desktop-portal launch helpers (virus class)"
  echo "OK   systemctl · cover.sh · desk-scan · curl 127 · typed URLs"
  echo
  bar 66
  echo "SERVICES (persistent)"
  status_unit bgrtx-datacenter.service
  status_unit grok-orphan-kill.timer
  status_unit bgf-reinstant.timer
  status_unit bgf-reinstant.service
  echo
  if systemctl is-active --quiet bgrtx-datacenter.service 2>/dev/null; then
    code=$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 1 http://127.0.0.1:8766/ 2>/dev/null || echo fail)
    echo "  datacenter HTTP $code  bind=127.0.0.1:8766  (local SPV · not public site)"
    print_url "http://127.0.0.1:8766/clean.html"
    print_url "http://127.0.0.1:8766/"
  else
    echo "  datacenter DOWN"
  fi
  echo
  bar 66
  echo "BGF REINSTANT (last cook)"
  if [[ -f "$JSON" ]]; then
    python3 - "$JSON" <<'PY' 2>/dev/null || cat "$JSON"
import json,sys
p=sys.argv[1]
d=json.load(open(p))
b,a,g=d.get("before",{}),d.get("after",{}),d.get("bgf",{})
print(f"  law:     {d.get('law','')}")
print(f"  before:  avail={b.get('mem_avail_kb')} free={b.get('mem_free_kb')} cached={b.get('cached_kb')} load={b.get('loadx100')} mhz={b.get('mhz')} temp_mC={b.get('temp_mC')}")
print(f"  after:   avail={a.get('mem_avail_kb')} free={a.get('mem_free_kb')} cached={a.get('cached_kb')} load={a.get('loadx100')} mhz={a.get('mhz')} temp_mC={a.get('temp_mC')}")
print(f"  BGF Δ:   mem_avail={g.get('mem_avail')} mem_free={g.get('mem_free')} cached={g.get('cached')} load={g.get('load')} mhz={g.get('mhz')} temp={g.get('temp_mC')}")
print(f"  free_spv={d.get('free_spv')}  log={d.get('log','')}")
PY
    echo "  file: $JSON"
  else
    echo "  (no $JSON yet · run: desk-clean cook)"
  fi
  echo
  bar 66
  echo "TIMERS"
  systemctl list-timers --no-pager 'bgf-*' 'grok-*' 2>/dev/null | sed 's/^/  /' || true
  echo
  bar 66
  echo "XDG VIRUS SURFACE (desk ban · do not launch · no pgrep -f)"
  xdg_n=0
  portal_n=0
  for d in /proc/[0-9]*; do
    [[ -r "$d/comm" ]] || continue
    c=$(cat "$d/comm" 2>/dev/null || true)
    case "$c" in
      xdg-open) xdg_n=$((xdg_n + 1)) ;;
      xdg-desktop-portal|xdg-document-portal|xdg-permission-store) portal_n=$((portal_n + 1)) ;;
    esac
  done
  echo "  xdg-open procs:           $xdg_n   (should be 0 · virus)"
  echo "  xdg-portal family procs:  $portal_n   (DE plumbing · not our launch path)"
  if [[ -x /usr/bin/xdg-open ]]; then
    echo "  binary present: /usr/bin/xdg-open  · NEVER use for desk open"
  else
    echo "  binary: absent or not /usr/bin/xdg-open"
  fi
  echo
  bar 66
  echo "ORPHAN REAPER (last lines)"
  if [[ -f "$ORPHAN_LOG" ]]; then
    tail -n 6 "$ORPHAN_LOG" 2>/dev/null | sed 's/^/  /' || true
  else
    echo "  (no log yet)"
  fi
  echo
  bar 66
  echo "COMMANDS"
  cat <<'CMD'
  desk-clean            this interface
  desk-clean cook       systemctl start bgf-reinstant.service (BGF reinstant)
  desk-clean orphan     run grok-orphan-kill now (+ kill xdg-open)
  desk-clean scan       magazine desk-scan forensics walk
  desk-clean status     units only
  desk-clean ban-xdg    kill stray xdg-open · print ban
  desk-clean bgl        BGL secure · clean ALL surfaces · field AV
  desk-clean url        print local clean URLs (no launch)
CMD
  echo
  echo "PUBLIC site remains https://biggrinrtx.com/ (WP Atomic · independent)"
  echo "LOCAL clean UI   http://127.0.0.1:8766/clean.html  (type URL · no xdg)"
}

cmd_status() {
  status_unit bgrtx-datacenter.service
  status_unit grok-orphan-kill.timer
  status_unit bgf-reinstant.timer
  status_unit bgf-reinstant.service
  systemctl list-timers --no-pager 'bgf-*' 'grok-*' 2>/dev/null || true
}

cmd_cook() {
  echo "BGF REINSTANT · systemctl start bgf-reinstant.service"
  systemctl start bgf-reinstant.service
  systemctl --no-pager --full status bgf-reinstant.service 2>&1 | head -22
  echo
  [[ -f "$JSON" ]] && echo "wrote $JSON" && cat "$JSON"
}

# kill by /proc/comm only · never pgrep -f (agent shell sabotage)
kill_comm() {
  local want=$1 killed=0 pid c
  for d in /proc/[0-9]*; do
    pid=${d#/proc/}
    [[ -r "$d/comm" ]] || continue
    c=$(cat "$d/comm" 2>/dev/null || true)
    [[ "$c" == "$want" ]] || continue
    echo "  KILL $want pid=$pid"
    kill -TERM "$pid" 2>/dev/null || true
    sleep 0.05
    kill -KILL "$pid" 2>/dev/null || true
    killed=$((killed + 1))
  done
  echo "  killed_$want=$killed"
}

cmd_orphan() {
  echo "ORPHAN + XDG-OPEN REAP · /proc/comm only"
  kill_comm xdg-open
  if [[ -x "$XROOT/RTXLayer/bin/grok-orphan-kill.sh" ]]; then
    "$XROOT/RTXLayer/bin/grok-orphan-kill.sh"
  elif [[ -x /usr/local/bin/grok-orphan-kill ]]; then
    /usr/local/bin/grok-orphan-kill
  else
    echo "missing grok-orphan-kill" >&2
    return 1
  fi
}

cmd_scan() {
  local s="${HOME}/Desktop/biggrinrtx-magazine/bin/desk-scan"
  if [[ -x "$s" ]]; then
    exec "$s" "$XROOT"
  else
    echo "missing desk-scan" >&2
    return 1
  fi
}

cmd_ban_xdg() {
  echo "BAN · xdg-open is virus for this desk"
  echo "  · never open pages with xdg-open"
  echo "  · type URLs · browser tab you already own · KateRTX/ESSIE"
  echo "  · no pgrep -f · kill by /proc/comm only"
  kill_comm xdg-open
}

cmd_url() {
  print_url "http://127.0.0.1:8766/clean.html"
  print_url "http://127.0.0.1:8766/"
  print_url "https://biggrinrtx.com/source-desk/"
  print_url "https://biggrinrtx.com/"
  echo "(do not xdg-open · virus)"
}

case "$c" in
  ui|show|interface|"") cmd_ui ;;
  cook|reinstant|clean) cmd_cook ;;
  orphan|reap) cmd_orphan ;;
  scan|forens) cmd_scan ;;
  status|st) cmd_status ;;
  ban-xdg|ban|virus) cmd_ban_xdg ;;
  bgl|secure|field-av) exec bash "${XROOT}/Build/bgl-secure.sh" ;;
  url|urls) cmd_url ;;
  help|-h|--help)
    echo "desk-clean [ui|cook|orphan|scan|status|ban-xdg|url]"
    ;;
  *) echo "unknown: $c · desk-clean help" >&2; exit 2 ;;
esac
