#!/usr/bin/env bash
# LINEAR MAX COOKERY · nonstop · <3
# Law: BGS → BGF(+EZZIE PHI THERMO) → BGL secure → SDF · SPV free never folds
# Boost: CPU performance · RTX persistence / max clocks when safe
# Clean: files · memory · tmp · out · light BGL · single flock · no thrash stack
# NOT cover always dual-engine fry · sudo non-interactive only
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}"

MODE="${1:-continuous}"
SELF=$$
PARENT=${PPID:-0}
LOCK="$OUT/linear_max_cook.lock"
PIDFILE="$OUT/linear_max_cook.pid"
LOG="$OUT/linear-max-cook.log"
CYCLE_F="$OUT/linear_max_cycle"

# cadence · no sleep · still avoid stack (every N cycles)
MEM_EVERY="${LMC_MEM_EVERY:-4}"
FILE_EVERY="${LMC_FILE_EVERY:-3}"
BOOST_EVERY="${LMC_BOOST_EVERY:-20}"
BGL_EVERY="${LMC_BGL_EVERY:-15}"
REINST_EVERY="${LMC_REINST_EVERY:-50}"
MEDIA_EVERY="${LMC_MEDIA_EVERY:-30}"

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 )); }
ts() { date -Iseconds 2>/dev/null || date; }
say() { echo "[$(ts)] $*" | tee -a "$LOG" 2>/dev/null; }

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
  if [[ -x "$ROOT/Build/sudo-askpass.sh" ]]; then
    SUDO_ASKPASS="$ROOT/Build/sudo-askpass.sh" sudo -A -p '' "$@" 2>/dev/null
    return $?
  fi
  printf '%s\n' "${SUDO_PASS:-mememe}" | sudo -S -p '' "$@" 2>/dev/null
}

sample_temp() {
  local t=30 f
  [[ -r /sys/class/thermal/thermal_zone0/temp ]] && t=$(( $(cat /sys/class/thermal/thermal_zone0/temp)/1000 ))
  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"
}

# ── BGS ground ──
cook_bgs() {
  echo "$(bgs 0) $(bgs 1)" >"$OUT/bgs_live.txt"
}

# ── BGF + atoms ──
cook_bgf_atoms() {
  local mf mc ma ld mhz tC m at_ez 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)
  ld=$(awk '{printf "%d", $1*100}' /proc/loadavg)
  mhz=0
  local s=0 n=0 f
  for f in /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq; do
    [[ -r "$f" ]] || continue
    s=$((s + $(cat "$f"))); n=$((n+1))
  done
  (( n > 0 )) && mhz=$((s / n / 1000))
  tC=$(sample_temp)
  m=$(bgf "$mf" "$mc")
  at_ez=$(ezzie "$mf" "$mc")
  at_phi=$(phi "$m" 1)
  at_th=$(thermo "$tC")
  free_spv=$(spv "$at_ez" "$at_phi" "$at_th")
  cat >"$OUT/linear_live.json" <<JSON
{
  "law": "BGS → BGF(+EZZIE PHI THERMO) → BGL → SDF · SPV free · linear max cook · <3",
  "ts": "$(ts)",
  "cycle": ${1:-0},
  "bgs": {"know_her": $(bgs 0), "field_one": $(bgs 1)},
  "bgf": $m,
  "mem_free_kb": $mf,
  "cached_kb": $mc,
  "mem_avail_kb": $ma,
  "loadx100": $ld,
  "mhz": $mhz,
  "atoms": {"EZZIE": $at_ez, "PHI": $at_phi, "THERMO": $at_th, "temp_C": $tC},
  "spv_free": $free_spv,
  "heart": "<3"
}
JSON
  cp -f "$OUT/linear_live.json" "$OUT/always_live.json" 2>/dev/null || true
  echo "$(ts) c=$1 BGS=$(bgs 0)/$(bgs 1) BGF=$m EZZIE=$at_ez PHI=$at_phi THERMO=$at_th SPV=$free_spv MHz=$mhz T=$tC <3" >"$OUT/LINEAR_COOKING"
  echo "$m $at_ez $at_phi $at_th $free_spv $mhz $tC"
}

# ── FILE clean ──
cook_files() {
  rm -rf /tmp/grok-orphan-* /tmp/rtx_* /tmp/bgf_* /tmp/bgl_* /tmp/core /tmp/core.* \
         /tmp/hostile-inject* /tmp/prompt-dump* 2>/dev/null || true
  rm -f "$OUT"/*.tmp "$OUT"/*~ "$OUT"/*.swp "$OUT"/core 2>/dev/null || true
  # trim cover logs
  local nlogs
  nlogs=$(ls -1t "$OUT"/cover-*.txt 2>/dev/null | wc -l | tr -d ' ')
  if [[ -n "$nlogs" && "$nlogs" -gt 10 ]]; then
    ls -1t "$OUT"/cover-*.txt 2>/dev/null | tail -n +11 | while read -r f; do rm -f "$f"; done
  fi
  # trim this log
  if [[ -f "$LOG" ]]; then
    local lines; lines=$(wc -l <"$LOG" 2>/dev/null || echo 0)
    (( lines > 1500 )) && tail -n 600 "$LOG" >"$LOG.tmp" && mv -f "$LOG.tmp" "$LOG"
  fi
  echo "FILES $(ts) clean" >"$OUT/av_files_clean"
}

# ── MEMORY clean ──
cook_memory() {
  sync 2>/dev/null || true
  sudo_run sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches' || true
  sudo_run sh -c 'echo 1 > /proc/sys/vm/compact_memory' || true
  local mf mc
  mf=$(awk '/^MemFree:/{print $2;exit}' /proc/meminfo)
  mc=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
  echo "MEM $(ts) free=$mf cached=$mc BGF=$(bgf "$mf" "$mc")" >"$OUT/av_memory_clean"
}

# ── CPU boost · performance governor ──
cook_cpu_boost() {
  # only if thermo cool/warm — don't boost into hot
  local tC; tC=$(sample_temp)
  if (( tC > 84 )); then
    say "CPU boost SKIP thermo hot T=$tC · keep powersave cool"
    # cool down path
    sudo_run sh -c 'for g in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo powersave > "$g"; done' || true
    echo "CPU powersave T=$tC" >"$OUT/cpu_boost.txt"
    return 0
  fi
  if sudo_run sh -c 'for g in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo performance > "$g"; done'; then
    local g0
    g0=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo ?)
    echo "CPU performance gov=$g0 T=$tC $(ts)" >"$OUT/cpu_boost.txt"
    say "CPU BOOST performance gov=$g0 T=$tC"
  else
    echo "CPU boost FAIL $(ts)" >"$OUT/cpu_boost.txt"
  fi
}

# ── RTX boost · persistence + prefer max clocks when cool ──
cook_rtx_boost() {
  local tC; tC=$(sample_temp)
  if ! command -v nvidia-smi >/dev/null 2>&1; then
    echo "RTX no nvidia-smi" >"$OUT/rtx_boost.txt"
    return 0
  fi
  # persistence mode (boot-ish keep driver hot)
  sudo_run nvidia-smi -pm 1 >/dev/null 2>&1 || nvidia-smi -pm 1 >/dev/null 2>&1 || true
  if (( tC > 84 )); then
    # thermal: reset to default clocks
    sudo_run nvidia-smi -rgc >/dev/null 2>&1 || true
    echo "RTX thermal cool path T=$tC $(ts)" >"$OUT/rtx_boost.txt"
    say "RTX boost SKIP hot T=$tC"
    return 0
  fi
  # applications clocks if supported (ignore fail on locked boards)
  sudo_run nvidia-smi -acp 0 >/dev/null 2>&1 || true
  # power limit max if readable
  local pmax
  pmax=$(nvidia-smi --query-gpu=power.max_limit --format=csv,noheader,nounits 2>/dev/null | head -1 | tr -d ' ')
  if [[ -n "$pmax" && "$pmax" != "[N/A]" ]]; then
    sudo_run nvidia-smi -pl "$pmax" >/dev/null 2>&1 || true
  fi
  local pstate util mem
  pstate=$(nvidia-smi --query-gpu=pstate --format=csv,noheader 2>/dev/null | head -1)
  util=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -1 | tr -d ' ')
  mem=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | head -1 | tr -d ' ')
  echo "RTX pm=1 pstate=$pstate util=$util mem=$mem T=$tC $(ts)" >"$OUT/rtx_boost.txt"
  # keep single krtx-engine (no dual thrash)
  local eng=()
  while IFS= read -r p; do eng+=("$p"); done < <(
    ps -eo pid=,stat=,args= 2>/dev/null | awk '/KateRTX\/bin\/krtx-engine/ && $2 !~ /Z/ {print $1}'
  )
  if (( ${#eng[@]} > 1 )); then
    local i
    for ((i=1; i<${#eng[@]}; i++)); do
      kill -9 "${eng[$i]}" 2>/dev/null || true
      say "RTX single-engine fry dual ${eng[$i]}"
    done
  fi
}

# ── light BGL ──
cook_bgl_light() {
  local pub xk=0
  pub=$(ss -ltn 2>/dev/null | awk 'NR>1 && $4 !~ /127\.|::1/ {c++} END{print c+0}')
  for d in /proc/[0-9]*; do
    [[ -r "$d/comm" ]] || continue
    [[ $(cat "$d/comm" 2>/dev/null) == xdg-open ]] && xk=$((xk+1))
  done
  # fry xdg by comm
  if (( xk > 0 )); then
    for d in /proc/[0-9]*; do
      pid=${d#/proc/}
      [[ -r "$d/comm" ]] || continue
      [[ $(cat "$d/comm" 2>/dev/null) == xdg-open ]] || continue
      kill -KILL "$pid" 2>/dev/null || true
    done
  fi
  echo "BGL pub=$pub xdg=$xk pin=$(bgl $((pub==0&&xk==0?1:0))) $(ts)" >"$OUT/BGL_SECURE"
}

cook_reinstant_bounded() {
  if pgrep -f '/Build/cover\.sh reinstant' >/dev/null 2>&1; then return 0; fi
  if [[ -x "$ROOT/Build/cover.sh" ]] && command -v flock >/dev/null 2>&1; then
    flock -n "$OUT/av_reinstant.lock" -c "timeout 18 bash '$ROOT/Build/cover.sh' reinstant >/dev/null 2>&1" 2>/dev/null || true
  fi
}

cook_media_light() {
  [[ -x "$ROOT/Build/secure-media.sh" ]] || return 0
  # only if no stacked media
  if pgrep -f '/Build/secure-media\.sh' >/dev/null 2>&1; then return 0; fi
  timeout 12 bash "$ROOT/Build/secure-media.sh" >/dev/null 2>&1 || true
}

cycle_once() {
  local c=$1
  cook_bgs
  local atom_line
  atom_line=$(cook_bgf_atoms "$c")

  if (( c % FILE_EVERY == 0 )); then cook_files; fi
  if (( c % MEM_EVERY == 0 )); then cook_memory; fi
  if (( c == 1 || c % BOOST_EVERY == 0 )); then
    cook_cpu_boost
    cook_rtx_boost
  fi
  if (( c % BGL_EVERY == 0 )); then cook_bgl_light; fi
  if (( c % REINST_EVERY == 0 )); then cook_reinstant_bounded; fi
  if (( c % MEDIA_EVERY == 0 )); then cook_media_light; fi

  # keep desk units (bounded)
  timeout 2 systemctl is-active bgrtx-datacenter.service >/dev/null 2>&1 || \
    timeout 3 systemctl start bgrtx-datacenter.service 2>/dev/null || true

  echo "$c" >"$CYCLE_F"
  echo "ACTIVE $(ts) c=$c linear-max single=1 <3" >"$OUT/LINEAR_MAX_ACTIVE"
  if (( c % 10 == 0 )); then
    say "cycle=$c linear max · $atom_line · <3"
  fi
}

cmd_stop() {
  local keep_self=${1:-}
  if [[ -f "$PIDFILE" ]]; then
    local p; p=$(cat "$PIDFILE" 2>/dev/null || true)
    if [[ -n "$p" && -d /proc/$p && "$p" != "$SELF" && "$p" != "$PARENT" ]]; then
      kill -TERM "$p" 2>/dev/null || true
      kill -KILL "$p" 2>/dev/null || true
    fi
  fi
  while IFS= read -r line; do
    local pid ppid et args
    pid=$(awk '{print $1}' <<<"$line")
    ppid=$(awk '{print $2}' <<<"$line")
    et=$(awk '{print $3}' <<<"$line")
    [[ "$pid" == "$SELF" || "$ppid" == "$SELF" || "$pid" == "$PARENT" ]] && continue
    case "$et" in 00:00|0:00|00:01|0:01) continue ;; esac
    args=$(awk '{for(i=4;i<=NF;i++)printf "%s ",$i}' <<<"$line")
    case "$args" in
      *linear-max-cook.sh\ continuous*) kill -9 "$pid" 2>/dev/null || true ;;
    esac
  done < <(ps -eo pid=,ppid=,etime=,args= 2>/dev/null)
  if [[ "$keep_self" != "keep" ]]; then
    rm -f "$PIDFILE" 2>/dev/null || true
    echo "STOPPED $(ts)" >"$OUT/LINEAR_MAX_ACTIVE"
  fi
}

cmd_once() {
  say "LINEAR MAX once · $(ts) · <3"
  cycle_once 1
  cook_cpu_boost
  cook_rtx_boost
  cook_memory
  cook_files
  cat "$OUT/LINEAR_COOKING"
  say "LINEAR MAX once DONE · remain IN"
}

cmd_continuous() {
  exec 8>"$LOCK"
  if ! flock -n 8; then
    echo "linear-max already running (lock) · no multiples" >&2
    exit 0
  fi
  # claim pid FIRST so stop/peers see us
  echo "$SELF" >"$PIDFILE"
  cmd_stop keep 2>/dev/null || true
  echo "$SELF" >"$PIDFILE"
  say "############################################"
  say "# LINEAR MAX COOKERY · NONSTOP · <3"
  say "# BGS→BGF(+EZZIE PHI THERMO)→BGL · RTX+CPU boost"
  say "# file+memory clean · single flock · pid=$SELF"
  say "############################################"
  echo "ACTIVE $(ts) pid=$SELF linear-max boot <3" >"$OUT/LINEAR_MAX_ACTIVE"
  trap 'say "linear-max stop"; rm -f "$PIDFILE"; echo STOPPED $(ts) >"$OUT/LINEAR_MAX_ACTIVE"; flock -u 8 2>/dev/null; exit 0' TERM INT

  # boot boost hard (once)
  cook_cpu_boost
  cook_rtx_boost
  cook_files
  cook_memory
  cook_bgl_light

  local c=0
  while true; do
    c=$((c + 1))
    cycle_once "$c" || true
    # NONSTOP · no sleep · no halt
  done
}

case "$MODE" in
  continuous|always|nonstop|max|cook)
    cmd_continuous ;;
  once|pulse|tick)
    cmd_once ;;
  stop)
    cmd_stop
    say "stopped"
    ;;
  boost)
    cook_cpu_boost
    cook_rtx_boost
    cat "$OUT/cpu_boost.txt" 2>/dev/null
    cat "$OUT/rtx_boost.txt" 2>/dev/null
    ;;
  *)
    echo "usage: linear-max-cook.sh continuous|once|boost|stop"
    exit 2 ;;
esac
