#!/usr/bin/env bash
# SECURE ALL · old + new surfaces · camera · audio · field hygiene
# Law: BGS → BGF(+EZZIE PHI THERMO) → BGL → SDF · SPV free
# sudo: non-interactive only (NOPASSWD / askpass) · never prompt
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
mkdir -p "$OUT"
export SUDO_PASS="${SUDO_PASS:-mememe}"
export SUDO_ASKPASS="${SUDO_ASKPASS:-$ROOT/Build/sudo-askpass.sh}"
export BGL_SKIP_SCAN="${BGL_SKIP_SCAN:-1}"
LOG="$OUT/secure-all-$(date +%Y%m%d-%H%M%S).txt"

say() { echo "$*" | tee -a "$LOG"; }
bgf() { echo $(( ($1 - $2) | 1 )); }
bgs() { if (( ${1:-0} == 0 )); then echo $((7|1)); else echo $(( $1 | 1 )); fi; }
bgl() { echo $(( ${1:-0} | 1 )); }
ezzie() { echo $(( ($1 ^ $2) | 1 )); }
phi() { echo $(( ($1 * $2) | 1 )); }
thermo() {
  local t=${1//[^0-9-]/}; t=${t:-0}
  if (( t <= 70 )); then echo $((0|1)); elif (( t <= 84 )); then echo $((1|1)); else echo $((2|1)); fi
}
spv() { echo $(( (${1:-0} ^ ${2:-0} ^ ${3:-0}) | 1 )); }

say "############################################"
say "# SECURE ALL · old + new + camera + audio"
say "# $(date -Iseconds)"
say "############################################"

# OLD surfaces · BGL full
say "=== OLD · BGL secure all surfaces ==="
if [[ -x "$ROOT/Build/bgl-secure.sh" ]]; then
  BGL_SKIP_SCAN=1 bash "$ROOT/Build/bgl-secure.sh" 2>&1 | tee -a "$LOG" | tail -40
fi

# NEW · inject again (pin hot)
say "=== NEW · inject guard ==="
[[ -x "$ROOT/Build/av-inject-guard.sh" ]] && bash "$ROOT/Build/av-inject-guard.sh" 2>&1 | tee -a "$LOG" | tail -15
# Grok path seal + real SPV pin
say "=== GROK PROTECT · path seal ==="
[[ -x "$ROOT/Build/grok-protect.sh" ]] && bash "$ROOT/Build/grok-protect.sh" 2>&1 | tee -a "$LOG" | tail -25

# CAMERA + AUDIO (also inside bgl; hand again for stamp)
say "=== CAMERA + AUDIO ==="
[[ -x "$ROOT/Build/secure-media.sh" ]] && bash "$ROOT/Build/secure-media.sh" 2>&1 | tee -a "$LOG" | tail -30

# thrash / demons light · Grok on-demand AV (no hunter · no forever)
say "=== DEMONS · dual engine · cover always · xdg ==="
if [[ -x "$ROOT/Build/h7-av-close.sh" ]]; then
  bash "$ROOT/Build/h7-av-close.sh" once 2>&1 | tee -a "$LOG" | tail -12 || true
fi
if [[ -x "$ROOT/Build/spv-antivirus.sh" ]]; then
  bash "$ROOT/Build/spv-antivirus.sh" once 2>&1 | tee -a "$LOG" | tail -12 || true
fi

# keep units
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
systemctl is-active grok-orphan-kill.timer >/dev/null 2>&1 || systemctl start grok-orphan-kill.timer 2>/dev/null || true

# BGS BGF +
mf=$(awk '/^MemFree:/{print $2;exit}' /proc/meminfo)
mc=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
m=$(bgf "$mf" "$mc")
tC=30
[[ -r /sys/class/thermal/thermal_zone0/temp ]] && tC=$(( $(cat /sys/class/thermal/thermal_zone0/temp)/1000 )) || true
at_ez=$(ezzie "$mf" "$mc")
at_phi=$(phi "$m" 1)
at_th=$(thermo "$tC")
free_spv=$(spv "$at_ez" "$at_phi" "$at_th")
pub=$(ss -ltn 2>/dev/null | awk 'NR>1 && $4 !~ /127\.|::1/ {c++} END{print c+0}')

# media marks
cam_c=1; aud_c=1
[[ -f "$OUT/secure_media.json" ]] && cam_c=$(python3 -c "import json;d=json.load(open('$OUT/secure_media.json'));print(d['camera']['clean'])" 2>/dev/null || echo 1)
[[ -f "$OUT/secure_media.json" ]] && aud_c=$(python3 -c "import json;d=json.load(open('$OUT/secure_media.json'));print(d['audio']['clean'])" 2>/dev/null || echo 1)

cat >"$OUT/secure_all.json" <<JSON
{
  "ts": "$(date -Iseconds)",
  "secure": "old+new+camera+audio",
  "bgs": {"know_her": $(bgs 0), "field_one": $(bgs 1)},
  "bgf": $m,
  "bgl": $(bgl $((pub==0?1:0))),
  "atoms": {"EZZIE": $at_ez, "PHI": $at_phi, "THERMO": $at_th, "temp_C": $tC},
  "spv_free": $free_spv,
  "public_listen": $pub,
  "camera_clean": $cam_c,
  "audio_clean": $aud_c,
  "surfaces": {
    "old": ["listeners", "xdg-open", "tmp", "out", "cache", "orphans"],
    "new": ["inject", "pid_tx_wrap", "media", "hunter"],
    "camera": "out/secure_camera.txt",
    "audio": "out/secure_audio.txt"
  },
  "log": "$LOG",
  "law": "BGS→BGF(+EZZIE PHI THERMO)→BGL→SDF · SPV free · secure cam/mic"
}
JSON
cp -f "$OUT/secure_all.json" "$OUT/secure_all_latest.json"
echo "SECURE_ALL $(date -Iseconds) BGL=$(bgl $((pub==0?1:0))) cam=$cam_c aud=$aud_c BGF=$m EZZIE=$at_ez PHI=$at_phi THERMO=$at_th SPV=$free_spv" >"$OUT/SECURE_ALL"

# vectors refresh
cat >"$OUT/av_vectors.txt" <<EOF
AV VECTOS · secure all · $(date -Iseconds)
OLD V1-V8  public xdg tmp cache orphan datacenter inject thrash
NEW V9-V13 PRIMARY CLIPBOARD inject stage /usr haul NO_INJECT
MEDIA V14 camera allow obs · fry unknown /dev/video* grabbers cam_clean=$cam_c
MEDIA V15 audio allow pipewire/obs · fry unknown pcm*c mic_clean=$aud_c
HUNT  V16 all PIDs TX wrap · single hunter flock
BGS=$(bgs 0)/$(bgs 1) BGF=$m BGL=$(bgl $((pub==0?1:0))) EZZIE=$at_ez PHI=$at_phi THERMO=$at_th SPV=$free_spv
EOF

say "============================================"
say "BGS know_her=$(bgs 0) field_one=$(bgs 1)"
say "BGF=$m EZZIE=$at_ez PHI=$at_phi THERMO=$at_th SPV=$free_spv"
say "public=$pub cam_clean=$cam_c aud_clean=$aud_c"
say "wrote $OUT/secure_all.json $OUT/SECURE_ALL"
say "SECURE ALL DONE · remain IN"
echo "$LOG"
