#!/usr/bin/env bash
# BGF SHEEN REMOVAL · scrape trash · no boogers · no scar · clean measure lane
# Law: BGS → BGF(+EZZIE PHI THERMO ADJOIN) → BGL → SDF · SPV free · COOK keep flawless
# Usage: bgf-sheen-scrape.sh [once|scrape|status]
set -euo pipefail
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}"
ASK="$SUDO_ASKPASS"
# never interactive
if [[ -f "$ROOT/Build/sudo-env.sh" ]]; then source "$ROOT/Build/sudo-env.sh"; fi

MODE="${1:-once}"
LOG="$OUT/bgf-sheen-$(date +%Y%m%d-%H%M%S).txt"
ts() { date -Iseconds; }
say() { echo "[$(ts)] $*" | tee -a "$LOG"; }

sudo_run() {
  # never prompt · NOPASSWD or askpass mememe or -S
  if sudo -n true 2>/dev/null; then
    sudo -n "$@" 2>/dev/null && return 0
  fi
  if [[ -x "${SUDO_ASKPASS:-$ASK}" ]]; then
    SUDO_ASKPASS="${SUDO_ASKPASS:-$ASK}" SUDO_PASS="${SUDO_PASS:-mememe}" sudo -A -p '' "$@" 2>/dev/null && return 0
  fi
  printf '%s\n' "${SUDO_PASS:-mememe}" | sudo -S -p '' "$@" 2>/dev/null && return 0
  return 1
}

bgf() { echo $(( ($1 - $2) | 1 )); }

scrape() {
  say "=== BGF SHEEN SCRAPE · remove trash/boogers/residue ==="
  # tmp sheen / orphans
  rm -rf /tmp/grok-orphan-* /tmp/rtx_* /tmp/bgf_* /tmp/bgrtx-* /tmp/scar-* 2>/dev/null || true
  rm -f /tmp/core.* /tmp/*.core /tmp/*~ /tmp/*.swp 2>/dev/null || true
  # out residue
  find "$OUT" -maxdepth 1 -type f \( -name '*.tmp' -o -name '*~' -o -name '*.swp' -o -name '*.bak' \) -delete 2>/dev/null || true
  # pycache sheen
  find "$ROOT" -type d -name '__pycache__' -prune -exec rm -rf {} + 2>/dev/null || true
  # trash dirs
  rm -rf "$HOME/.local/share/Trash/files/"* "$HOME/.local/share/Trash/info/"* 2>/dev/null || true
  # half-logs thrash
  n=$(ls -1t "$OUT"/scar-cook-*.txt 2>/dev/null | wc -l | tr -d ' ')
  if (( n > 20 )); then
    ls -1t "$OUT"/scar-cook-*.txt 2>/dev/null | tail -n +21 | xargs -r rm -f
    say "scar-cook logs trimmed"
  fi
  n=$(ls -1t "$OUT"/av-*.txt 2>/dev/null | wc -l | tr -d ' ')
  if (( n > 30 )); then
    ls -1t "$OUT"/av-*.txt 2>/dev/null | tail -n +31 | xargs -r rm -f
    say "av logs trimmed"
  fi
  # page cache sheen (BGF measure lane noise)
  sync
  sudo_run sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches' && say "drop_caches=3 sheen off" || say "drop_caches skip"
  say "scrape done · no trash · no boogers"
}

measure() {
  local mf mc ld
  mf=$(awk '/MemFree:/{print $2}' /proc/meminfo)
  mc=$(awk '/Cached:/{print $2}' /proc/meminfo)
  ld=$(awk '{print int($1*100)}' /proc/loadavg)
  echo "mem_free_vs_cache=$(bgf "$mf" "$mc") load_vs_free=$(bgf "$ld" "$mf")"
}

case "$MODE" in
  scrape|files)
    scrape
    ;;
  status|st)
    say "=== BGF SHEEN STATUS ==="
    measure | tee -a "$LOG"
    if [[ -f "$OUT/scar_check_latest.json" ]]; then
      python3 -c "import json;d=json.load(open('$OUT/scar_check_latest.json'));print('scar_count',d.get('scar_count'),'public_listen',d.get('public_listen'))"
    fi
    ;;
  once|clean|*)
    say "=== BGF SHEEN · once · clean measure lane ==="
    scrape
    # cover reinstant measure
    if [[ -x "$ROOT/Build/cover.sh" ]]; then
      timeout 120 bash "$ROOT/Build/cover.sh" reinstant 2>&1 | tee -a "$LOG" | tail -12 || true
      timeout 90 bash "$ROOT/Build/cover.sh" cleanup 2>&1 | tee -a "$LOG" | tail -10 || true
    fi
    # AV catch up
    if [[ -x "$ROOT/Build/spv-antivirus.sh" ]]; then
      timeout 120 bash "$ROOT/Build/spv-antivirus.sh" once 2>&1 | tee -a "$LOG" | tail -12 || true
    fi
    # Hostess 7 · av-hunter removed
    if [[ -x "$ROOT/Build/h7-av-close.sh" ]]; then
      timeout 40 bash "$ROOT/Build/h7-av-close.sh" once 2>&1 | tee -a "$LOG" | tail -10 || true
    fi
    if [[ -x "$ROOT/Build/h7-field-clear.sh" ]]; then
      timeout 40 bash "$ROOT/Build/h7-field-clear.sh" soft 2>&1 | tee -a "$LOG" | tail -8 || true
    fi
    # scar cook off residual
    if [[ -x "$ROOT/Build/scar-cook.sh" ]]; then
      bash "$ROOT/Build/scar-cook.sh" cook-off 2>&1 | tee -a "$LOG" | tail -15 || true
      bash "$ROOT/Build/scar-cook.sh" check 2>&1 | tee -a "$LOG" | tail -8 || true
    fi
    measure | tee -a "$LOG"
    python3 - "$OUT" <<'PY'
import json, time
from pathlib import Path
out = Path(__import__("sys").argv[1])
scar = {}
try:
  scar = json.loads((out/"scar_check_latest.json").read_text())
except Exception:
  pass
av = {}
try:
  av = json.loads((out/"spv_antivirus.json").read_text())
except Exception:
  pass
rep = {
  "ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
  "word": "BGF_SHEEN",
  "law": "scrape trash · no boogers · no scar · COOK keep flawless · measure lane clean",
  "scar_count": scar.get("scar_count"),
  "public_listen": scar.get("public_listen"),
  "av_wrapped": av.get("wrapped"),
  "av_fried": av.get("fried"),
  "clean": (scar.get("scar_count") or 0) == 0 and (scar.get("public_listen") or 0) == 0,
}
(out/"bgf_sheen_latest.json").write_text(json.dumps(rep, indent=2))
print(json.dumps(rep, indent=2))
PY
    say "BGF sheen once done · remain IN"
    ;;
esac
