#!/usr/bin/env bash
# BGL secure · clean ALL surfaces · field hygiene AV (not commercial antivirus)
# Law: BGS → BGF → BGL secure/clean → SDF · SPV free · never fold
# NO pkill -f · NO xdg-open launch · 127 desk only
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
MAG="${HOME}/Desktop/biggrinrtx-magazine"
mkdir -p "$OUT"
LOG="$OUT/bgl-secure-$(date +%Y%m%d-%H%M%S).txt"
SUDO_PASS="${SUDO_PASS:-mememe}"

bgf() { echo $(( ($1 - $2) | 1 )); }
bgl() { echo $(( ${1:-0} | 1 )); }   # secure clean pin · surface|1
spv() { echo $(( (${1:-0} ^ ${2:-0} ^ ${3:-0}) | 1 )); }

say() { echo "$*" | tee -a "$LOG"; }

sudo_run() {
  if [[ "$(id -u)" -eq 0 ]]; then "$@"; return $?; fi
  if sudo -n true 2>/dev/null; then sudo -n "$@" 2>/dev/null; return $?; fi
  local ask="${ROOT}/Build/sudo-askpass.sh"
  if [[ -x "$ask" ]]; then
    SUDO_ASKPASS="$ask" SUDO_PASS="${SUDO_PASS:-mememe}" sudo -A -p '' "$@" 2>/dev/null
    return $?
  fi
  printf '%s\n' "${SUDO_PASS:-mememe}" | sudo -S -p '' "$@" 2>/dev/null
}

# kill by /proc/comm only
kill_comm() {
  local want=$1 n=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
    kill -TERM "$pid" 2>/dev/null || true
    sleep 0.05
    kill -KILL "$pid" 2>/dev/null || true
    n=$((n + 1))
  done
  echo "$n"
}

say "############################################"
say "# BGL SECURE · CLEAN ALL SURFACES · FIELD AV"
say "# $(date -Iseconds)"
say "############################################"
say "LAW: BGS → BGF → BGL secure/clean → SDF · SPV free · not commercial AV"

# --- surface 1: listeners ---
say "=== SURFACE · listeners ==="
pub=$(ss -ltn 2>/dev/null | awk 'NR>1 && $4 !~ /127\.|::1/ {c++} END{print c+0}')
loc=$(ss -ltn 2>/dev/null | awk 'NR>1 && $4 ~ /127\.|::1/ {c++} END{print c+0}')
say "public_listen=$pub  local_listen=$loc  BGL_public_quiet=$( [[ $pub -eq 0 ]] && echo 1 || echo 0 )"
if (( pub > 0 )); then
  say "WARN public listeners present · office law: close them"
  ss -ltn 2>/dev/null | awk 'NR==1 || $4 !~ /127\.|::1/' | tee -a "$LOG" || true
fi

# --- surface 2: xdg virus ---
say "=== SURFACE · xdg-open virus ==="
xk=$(kill_comm xdg-open)
say "xdg-open killed=$xk  BGL_xdg=$(bgl $((xk==0?1:0)) )"

# --- surface 3: tmp unclean ---
say "=== SURFACE · tmp unclean ==="
rm -rf /tmp/grok-orphan-* /tmp/rtx_* /tmp/amouranth* /tmp/never_fold* /tmp/bgf_* /tmp/bgl_* 2>/dev/null || true
rm -f /tmp/core /tmp/core.* /tmp/*.core 2>/dev/null || true
say "tmp residue cleared  BGL_tmp=$(bgl 1)"

# --- surface 4: out half-writes ---
say "=== SURFACE · out unclean ==="
rm -f "$OUT"/*.tmp "$OUT"/*~ "$OUT"/*.swp "$OUT"/core "$OUT"/core.* 2>/dev/null || true
# trim cover logs keep 12
nlogs=$(ls -1t "$OUT"/cover-*.txt 2>/dev/null | wc -l | tr -d ' ')
if [[ -n "$nlogs" && "$nlogs" -gt 12 ]]; then
  ls -1t "$OUT"/cover-*.txt 2>/dev/null | tail -n +13 | while read -r f; do rm -f "$f"; done
  say "cover logs trimmed"
fi
say "out clean  BGL_out=$(bgl 1)"

# --- surface 5: page cache (field hygiene cook) ---
say "=== SURFACE · page cache ==="
sync
if sudo_run sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'; then
  say "drop_caches=3 OK  BGL_cache=$(bgl 1)"
else
  say "drop_caches SKIP  BGL_cache=$(bgl 0)"
fi

# --- surface 6: orphan reaper (tree first · no /usr force) ---
say "=== SURFACE · field orphans ==="
if [[ -x "$ROOT/RTXLayer/bin/grok-orphan-kill.sh" ]]; then
  bash "$ROOT/RTXLayer/bin/grok-orphan-kill.sh" >>"$LOG" 2>&1 || true
  say "orphan reaper pass  BGL_orphan=$(bgl 1)"
elif [[ -x /usr/local/bin/grok-orphan-kill ]]; then
  /usr/local/bin/grok-orphan-kill >>"$LOG" 2>&1 || true
  say "orphan reaper pass (local bin)  BGL_orphan=$(bgl 1)"
else
  say "orphan reaper missing  BGL_orphan=$(bgl 0)"
fi

# --- surface 7: TEXT INJECT guard (Grok + you · desk end) ---
say "=== SURFACE · text inject guard (Grok + you) ==="
if [[ -x "$ROOT/Build/av-inject-guard.sh" ]]; then
  AV_INJECT_LOG="$OUT/av-inject-from-bgl.txt" bash "$ROOT/Build/av-inject-guard.sh" >>"$LOG" 2>&1 || true
  say "inject guard pass  BGL_inject=$(bgl 1)"
else
  say "inject guard missing  BGL_inject=$(bgl 0)"
fi

# --- surface 8: CAMERA + AUDIO media secure ---
say "=== SURFACE · camera + audio media secure ==="
if [[ -x "$ROOT/Build/secure-media.sh" ]]; then
  bash "$ROOT/Build/secure-media.sh" >>"$LOG" 2>&1 || true
  say "media secure pass  BGL_media=$(bgl 1)"
else
  say "media secure missing  BGL_media=$(bgl 0)"
fi

# --- surface 9: desk-scan field AV walk (optional short) ---
say "=== SURFACE · desk-scan field hygiene AV ==="
if [[ "${BGL_SKIP_SCAN:-0}" == "1" ]]; then
  say "desk-scan skipped (BGL_SKIP_SCAN=1)  BGL_scan=$(bgl 1)"
elif [[ -x "$MAG/bin/desk-scan" ]]; then
  DESK_SCAN_MAX="${DESK_SCAN_MAX:-600}" "$MAG/bin/desk-scan" "$ROOT" >>"$LOG" 2>&1 || true
  say "desk-scan walk done  BGL_scan=$(bgl 1)"
else
  say "desk-scan missing  BGL_scan=$(bgl 0)"
fi

# --- measure after clean ---
mf=$(awk '/^MemFree:/{print $2;exit}' /proc/meminfo)
mc=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
say "=== BGF after BGL clean ==="
say "MemFree=$mf Cached=$mc BGF_free_vs_cache=$(bgf "$mf" "$mc")"

# --- composite BGL secure mark ---
# surfaces: pub quiet, xdg, tmp, out, cache, orphan, scan → free mix
bgl_all=$(spv $((pub==0?1:0)) $((xk==0?1:0)) 1)
say "BGL SECURE mark free_spv=$bgl_all  (rides measure · never folds)"
say "field hygiene AV updated · NOT commercial antivirus · remain IN"

cat >"$OUT/bgl_secure.json" <<JSON
{
  "law": "BGS → BGF → BGL secure/clean → SDF · SPV free · never fold",
  "ts": "$(date -Iseconds)",
  "av": "field hygiene · not commercial antivirus",
  "surfaces": {
    "public_listen": $pub,
    "local_listen": $loc,
    "public_quiet": $((pub==0?1:0)),
    "xdg_open_killed": $xk,
    "tmp_clean": 1,
    "out_clean": 1,
    "text_inject_guard": 1,
    "camera_audio": 1
  },
  "inject": "PRIMARY clear · CLIPBOARD on pattern · no /usr haul to Grok · NO_INJECT pin",
  "media": "out/secure_media.json · keep obs/pipewire · fry unknown cam/mic",
  "bgf": {"mem_free_kb": $mf, "cached_kb": $mc, "free_vs_cache": $(bgf "$mf" "$mc")},
  "bgl": $bgl_all,
  "log": "$LOG"
}
JSON
cp -f "$OUT/bgl_secure.json" "$OUT/bgl_latest.json"
echo "CLEAN $(date -Iseconds) BGL=$bgl_all pub=$pub" >"$OUT/BGL_SECURE"
say "wrote $OUT/bgl_secure.json"
say "BGL SECURE DONE · all surfaces · field AV"
echo "$LOG"
