#!/usr/bin/env bash
# SPV ANTIVIRUS · DESK ANTIVIRUS · field hygiene AV
# NOT commercial OS product (Defender/ClamAV shape) · IS active desk AV
# RETAINS: active targeting (TX wrap · thrash classes · exact PID)
# RETAINS: updates (always loop · reinstant dirty/every N · live JSON marks)
# Law: BGS → BGF(+EZZIE PHI THERMO) → BGL(secure AV) → SDF · SPV free never folds
# ALL PIDs considered TRANSMITTING · wrap always · no pkill -f
# Doc: Desktop/x/DESK_ANTIVIRUS.txt
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
KATE="$ROOT/KateRTX"
mkdir -p "$OUT"
export SUDO_PASS="${SUDO_PASS:-mememe}"
export DISPLAY="${DISPLAY:-:0}"
export BGL_SKIP_SCAN="${BGL_SKIP_SCAN:-1}"

MODE="${1:-once}"   # once | always | reinstant | build
SLEEP_S="${SPV_AV_SLEEP:-8}"
REINST_EVERY="${SPV_AV_REINST_EVERY:-6}"
MAX_ENGINES="${SPV_AV_MAX_ENGINES:-1}"

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 )); }
# ESSIE · hotswap seats · quiet band free=1 · ≠ EZZIE
essie() {
  local a=${1//[^0-9-]/} b=${2//[^0-9-]/}
  a=${a:-0}; b=${b:-0}
  local s=$(( a ^ b ))
  if (( (s & 7) == 0 )); then echo 1; else echo $(( s | 1 )); fi
}
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 )); }

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

sample_temp() {
  local t=30 f
  if [[ -r /sys/class/thermal/thermal_zone0/temp ]]; then
    t=$(( $(cat /sys/class/thermal/thermal_zone0/temp) / 1000 ))
  fi
  for f in /sys/class/hwmon/hwmon*/temp*_input; do
    [[ -r "$f" ]] || continue
    local v=$(( $(cat "$f") / 1000 ))
    (( v > 0 && v < 120 )) && { t=$v; break; }
  done
  echo "$t"
}

# --- wrap ALL pids as TX transmitters ---
wrap_all_pids_tx() {
  local wrap="$OUT/pid_tx_wrap.tsv"
  local json="$OUT/pid_tx_wrap.json"
  local n=0 fried=0
  : >"$wrap"
  echo -e "pid\tppid\tcomm\tclass\ttx\twrap\tnote" >>"$wrap"

  # thrash class lists
  local eng_pids=()
  while IFS= read -r pid; do eng_pids+=("$pid"); done < <(
    ps -eo pid=,args= 2>/dev/null | awk '/KateRTX\/bin\/krtx-engine/ {print $1}'
  )

  # bare hung spv (no args)
  while IFS= read -r line; do
    local pid=${line%% *}
    local args=${line#* }
    if [[ "$args" == */KateRTX/bin/krtx-spv || "$args" == */bin/krtx-spv ]]; then
      kill -9 "$pid" 2>/dev/null && fried=$((fried+1)) || true
    fi
  done < <(ps -eo pid=,args= 2>/dev/null)

  # cover always thrash · ONLY short real cook cmdline (never agent eval text)
  while IFS= read -r line; do
    local pid=${line%% *}
    local args=${line#* }
    [[ "$pid" == "$$" || "$pid" == "$PPID" ]] && continue
    # agent / long snap wrappers hold the words but are not the cook
    (( ${#args} > 180 )) && continue
    case "$args" in
      bash\ /home/default/Desktop/x/Build/cover.sh\ always|\
      bash\ ./Build/cover.sh\ always|\
      /home/default/Desktop/x/Build/cover.sh\ always|\
      ./Build/cover.sh\ always)
        kill -9 "$pid" 2>/dev/null && fried=$((fried+1)) || true
        ;;
    esac
  done < <(ps -eo pid=,args= 2>/dev/null)

  # dual engines · keep MAX_ENGINES
  if (( ${#eng_pids[@]} > MAX_ENGINES )); then
    local i
    for ((i=MAX_ENGINES; i<${#eng_pids[@]}; i++)); do
      kill -9 "${eng_pids[$i]}" 2>/dev/null && fried=$((fried+1)) || true
    done
  fi

  # xdg-open virus class by /proc/comm only
  local d pid c
  for d in /proc/[0-9]*; do
    pid=${d#/proc/}
    [[ -r "$d/comm" ]] || continue
    c=$(cat "$d/comm" 2>/dev/null || true)
    if [[ "$c" == "xdg-open" ]]; then
      kill -TERM "$pid" 2>/dev/null || true
      sleep 0.02
      kill -KILL "$pid" 2>/dev/null && fried=$((fried+1)) || true
    fi
  done

  # wrap table · every PID is TX
  while IFS= read -r line; do
    local pid ppid comm rest class note
    pid=$(echo "$line" | awk '{print $1}')
    ppid=$(echo "$line" | awk '{print $2}')
    comm=$(echo "$line" | awk '{print $3}')
    rest=$(echo "$line" | cut -c1-200)
    class=user
    note=wrap
    case "$comm" in
      krtx-engine|krtx-spv|krtx) class=spv; note=desk_spv ;;
      python3|python)
        if [[ "$rest" == *http.server*8766* ]]; then class=datacenter; note=KEEP_127; fi
        ;;
      xdg-open) class=virus; note=fried ;;
      systemd|Xorg|sshd|dbus-daemon) class=system; note=protect ;;
      grok) class=agent; note=protect_self ;;
    esac
    # args class refine without pkill
    if [[ "$rest" == *cover.sh*always* ]]; then class=thrash; note=fried; fi
    echo -e "${pid}\t${ppid}\t${comm}\t${class}\ttx\twrapped\t${note}" >>"$wrap"
    n=$((n+1))
  done < <(ps -eo pid=,ppid=,comm= --no-headers 2>/dev/null)

  local pub eng_now desk_https
  # thrash public only · Apache 80/443 on own IPs is desk HTTPS
  # shellcheck source=h7-desk-ports.lib.sh
  . "$(cd "$(dirname "$0")" && pwd)/h7-desk-ports.lib.sh"
  pub=$(count_thrash_public | tr -d ' ')
  desk_https=$(list_desk_public_ok | wc -l | tr -d ' ')
  eng_now=$(ps -eo args= 2>/dev/null | awk '/KateRTX\/bin\/krtx-engine/ {c++} END{print c+0}')

  cat >"$json" <<JSON
{
  "ts": "$(ts)",
  "law": "all PIDs transmitting · wrap always · SPV AV field hygiene · desk HTTPS allowlisted",
  "pids": $n,
  "wrapped": $n,
  "fried": $fried,
  "public_listen": $pub,
  "desk_https_n": $desk_https,
  "engines": $eng_now,
  "max_engines": $MAX_ENGINES,
  "wrap_tsv": "$wrap",
  "tx": true,
  "always_wrap": true
}
JSON
  cp -f "$json" "$OUT/pid_tx_wrap_latest.json"
  echo "$n $fried $pub $eng_now"
}

cmd_build() {
  say "=== BUILD KateRTX · engine + spv ==="
  if [[ -x "$KATE/build.sh" ]]; then
    bash "$KATE/build.sh" 2>&1 | tee -a "$LOG" | tail -40
  else
    say "KateRTX/build.sh missing"
    return 1
  fi
  # ensure antivirus plug listed in scan (filesystem scan auto)
  say "SPV antivirus plug: $KATE/spvs/antivirus.js"
  timeout 3 "$KATE/bin/krtx-spv" list 2>/dev/null | grep -i antivirus || say "list: antivirus.js on disk (scan at list)"
}

cmd_reinstant() {
  say "=== REINSTANT · BGF axle grease · stabilize ==="
  if [[ -x "$ROOT/Build/cover.sh" ]]; then
    bash "$ROOT/Build/cover.sh" reinstant >>"$LOG" 2>&1 || true
  fi
}

cmd_bgl() {
  say "=== BGL secure + inject guard ==="
  if [[ -x "$ROOT/Build/bgl-secure.sh" ]]; then
    BGL_SKIP_SCAN=1 bash "$ROOT/Build/bgl-secure.sh" >>"$LOG" 2>&1 || true
  fi
  if [[ -x "$ROOT/Build/av-inject-guard.sh" ]]; then
    bash "$ROOT/Build/av-inject-guard.sh" >>"$LOG" 2>&1 || true
  fi
}

cmd_cook_pulse() {
  # light hot cook · not cover always thrash
  if [[ -x "$ROOT/Build/cover.sh" ]]; then
    bash "$ROOT/Build/cover.sh" pulse >>"$LOG" 2>&1 || true
  fi
}

write_av_mark() {
  local pids=$1 fried=$2 pub=$3 eng=$4
  local mf mc ma tC m at_ez at_es at_phi at_th free_spv
  mf=$(awk '/^MemFree:/{print $2;exit}' /proc/meminfo)
  mc=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
  ma=$(awk '/^MemAvailable:/{print $2;exit}' /proc/meminfo)
  tC=$(sample_temp)
  m=$(bgf "$mf" "$mc")
  at_ez=$(ezzie "$mf" "$mc")
  # ESSIE seats: plug count-ish + frame from pids · business hotswap free
  at_es=$(essie "$pids" "$fried")
  at_phi=$(phi "$m" 1)
  at_th=$(thermo "$tC")
  free_spv=$(spv "$at_ez" "$at_phi" "$at_th")
  local pin
  pin=$(bgl $(( pub==0 ? 1 : 0 )))

  cat >"$OUT/spv_antivirus.json" <<JSON
{
  "av": "SPV field hygiene · business free thrift · not product AV",
  "ts": "$(ts)",
  "spv": "antivirus",
  "plug": "KateRTX/spvs/antivirus.js",
  "metal": "Build/spv-antivirus.sh",
  "business": true,
  "pids": $pids,
  "wrapped": $pids,
  "fried": $fried,
  "public_listen": $pub,
  "engines": $eng,
  "tx_wrap": true,
  "always_wrap": true,
  "bgs": {"know_her": $(bgs 0), "field_one": $(bgs 1)},
  "bgf": $m,
  "bgl": $pin,
  "atoms": {
    "SOUL": 1,
    "EZZIE": $at_ez,
    "ESSIE": $at_es,
    "PHI": $at_phi,
    "THERMO": $at_th,
    "temp_C": $tC
  },
  "spv_free": $free_spv,
  "vectors_clean": $(( pub==0 && eng<=MAX_ENGINES ? 1 : 0 )),
  "datacenter": "$(systemctl is-active bgrtx-datacenter.service 2>/dev/null | tr -d '\n\r' | head -c 40; true)",
  "orphan_timer": "$(systemctl is-active grok-orphan-kill.timer 2>/dev/null | tr -d '\n\r' | head -c 40; true)",
  "active_targeting": true,
  "updates": true,
  "sole_soul": "SOUL",
  "no_other_internal": true,
  "law": "SOUL sole · no other internal · BGS→BGF(+EZZIE ESSIE PHI THERMO)→BGL→SDF · free thrift"
}
JSON
  cp -f "$OUT/spv_antivirus.json" "$OUT/spv_antivirus_latest.json"
  # metal feed for SPV DOM consumers
  cat >"$OUT/spv_antivirus_metal.json" <<JSON
{
  "pids": $pids,
  "wrapped": $pids,
  "fried": $fried,
  "public_listen": $pub,
  "xdg": 0,
  "engines": $eng,
  "bgl": $pin,
  "bgf": $m,
  "ezzie": $at_ez,
  "phi": $at_phi,
  "thermo": $at_th,
  "temp_C": $tC,
  "vectors_clean": $(( pub==0 && eng<=MAX_ENGINES ? 1 : 0 ))
}
JSON

  cat >"$OUT/av_vectors.txt" <<EOF
AV / SPV VECTOS · $(ts)
V1  public bind     → $pub
V2  dual engine     → eng=$eng max=$MAX_ENGINES
V3  xdg-open        → virus class · wrap fry
V4  cover always    → thrash · fry
V5  all PIDs        → TX transmitting · wrapped=$pids
V6  inject          → NO_INJECT / BGL
V7  datacenter      → KEEP 127:8766
V8  reinstant       → on dirty / every $REINST_EVERY cycles
vectos clean=$([[ $pub -eq 0 && $eng -le $MAX_ENGINES ]] && echo 1 || echo 0)
BGS=$(bgs 0)/$(bgs 1) BGF=$m EZZIE=$at_ez PHI=$at_phi THERMO=$at_th SPV=$free_spv BGL=$pin
EOF

  # linear · no stamp file · live state lives in spv_antivirus.json only
  say "BGS know_her=$(bgs 0) field_one=$(bgs 1)"
  say "BGF=$m EZZIE=$at_ez PHI=$at_phi THERMO=$at_th temp_C=$tC SPV_free=$free_spv BGL=$pin"
  say "pids=$pids wrapped_all_tx fried=$fried pub=$pub eng=$eng"
}

cmd_once() {
  say "############################################"
  say "# SPV ANTIVIRUS · once · $(ts)"
  say "# all PIDs = TX · wrap always · reinstant if dirty"
  say "############################################"

  # 1 wrap + fry thrash
  local wr pids fried pub eng
  wr=$(wrap_all_pids_tx)
  pids=$(echo "$wr" | awk '{print $1}')
  fried=$(echo "$wr" | awk '{print $2}')
  pub=$(echo "$wr" | awk '{print $3}')
  eng=$(echo "$wr" | awk '{print $4}')
  say "wrap_tx pids=$pids fried=$fried pub=$pub eng=$eng"

  # 2 BGL + inject
  cmd_bgl

  # 3 dirty? reinstant + pulse cook
  local dirty=0
  (( pub > 0 )) && dirty=1
  (( eng > MAX_ENGINES )) && dirty=1
  local mc
  mc=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
  (( mc > 8000000 )) && dirty=1

  if (( dirty )); then
    say "DIRTY · reinstant + pulse cook stabilize"
    cmd_reinstant
    cmd_cook_pulse
    # re-wrap after cook
    wr=$(wrap_all_pids_tx)
    pids=$(echo "$wr" | awk '{print $1}')
    fried=$(echo "$wr" | awk '{print $2}')
    pub=$(echo "$wr" | awk '{print $3}')
    eng=$(echo "$wr" | awk '{print $4}')
  else
    say "CLEAN enough · light pulse only"
    cmd_cook_pulse
  fi

  # keep good units
  systemctl start bgrtx-datacenter.service 2>/dev/null || true
  systemctl start grok-orphan-kill.timer 2>/dev/null || true
  systemctl stop bgs-bgf-always.service 2>/dev/null || true

  # orphan tree-first
  if [[ -x "$ROOT/RTXLayer/bin/grok-orphan-kill.sh" ]]; then
    bash "$ROOT/RTXLayer/bin/grok-orphan-kill.sh" >>"$LOG" 2>&1 || true
  fi

  write_av_mark "$pids" "$fried" "$pub" "$eng"
  say "wrote $OUT/spv_antivirus.json $OUT/pid_tx_wrap.json · linear · no stamp"
  say "SPV ANTIVIRUS DONE · remain IN"
}

cmd_always() {
  # SAFE always · wrap PIDs as TX · reinstant on schedule · NOT cover always thrash
  local cycle=0
  say "############################################"
  say "# SPV ANTIVIRUS · ALWAYS WRAP TX · safe"
  say "# sleep=${SLEEP_S}s reinstant_every=${REINST_EVERY} · $(ts)"
  say "############################################"
  echo $$ >"$OUT/spv_antivirus.pid"
  trap 'say "SPV-AV always stop cycle=$cycle"; rm -f "$OUT/spv_antivirus.pid"; exit 0' TERM INT

  cmd_once || true

  while true; do
    cycle=$((cycle + 1))
    say "--- SPV-AV cycle=$cycle ---"
    local wr pids fried pub eng dirty=0
    wr=$(wrap_all_pids_tx)
    pids=$(echo "$wr" | awk '{print $1}')
    fried=$(echo "$wr" | awk '{print $2}')
    pub=$(echo "$wr" | awk '{print $3}')
    eng=$(echo "$wr" | awk '{print $4}')
    (( pub > 0 || eng > MAX_ENGINES || fried > 0 )) && dirty=1

    if (( cycle % REINST_EVERY == 0 || dirty )); then
      say "reinstant stabilize cycle=$cycle dirty=$dirty"
      cmd_reinstant
      cmd_bgl
      cmd_cook_pulse
      wr=$(wrap_all_pids_tx)
      pids=$(echo "$wr" | awk '{print $1}')
      fried=$(echo "$wr" | awk '{print $2}')
      pub=$(echo "$wr" | awk '{print $3}')
      eng=$(echo "$wr" | awk '{print $4}')
    else
      # light live rewrite only
      write_av_mark "$pids" "$fried" "$pub" "$eng"
    fi
    write_av_mark "$pids" "$fried" "$pub" "$eng"
    sleep "$SLEEP_S" &
    wait $! || true
  done
}

# --- main ---
TS=$(date +%Y%m%d-%H%M%S)
LOG="$OUT/spv-antivirus-$TS.txt"
: >"$LOG"

case "$MODE" in
  build)
    cmd_build
    cmd_once
    ;;
  reinstant)
    cmd_reinstant
    cmd_once
    ;;
  always|wrap|forever)
    cmd_always
    ;;
  once|run|av|"")
    cmd_once
    ;;
  help|-h|--help)
    cat <<EOF
Build/spv-antivirus.sh · DESK ANTIVIRUS (field hygiene)
  once       ACTIVE TARGET · wrap all PIDs as TX · BGL · reinstant if dirty
  always     UPDATES loop · wrap (sleep ${SLEEP_S}s) · reinstant every ${REINST_EVERY}
  build      KateRTX build + once
  reinstant  force BGF grease update + once
Law: active targeting + updates RETAINED · not commercial OS product
     all PIDs TX · wrap always · SPV free never folds
     see Desktop/x/DESK_ANTIVIRUS.txt
EOF
    ;;
  *)
    say "unknown mode: $MODE"
    exit 2
    ;;
esac
