#!/usr/bin/env bash
# iron_see · see inside host iron · BGF measure only · no fold · free SPV unlimited ride
# TV/HDMI · GPU power/fan · CPU thermo · RAPL · net · always-cook pulse
# PSU wall: honest · no fake ATX telepathy unless hwmon exposes it
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
mkdir -p "$OUT"
LOG="$OUT/iron_see-$(date +%Y%m%d-%H%M%S).txt"
SUDO_PASS="${SUDO_PASS:-mememe}"

bgf() { echo $(( ($1 - $2) | 1 )); }
spv() { echo $(( (${1//[^0-9-]/0} ^ ${2//[^0-9-]/0} ^ ${3//[^0-9-]/0}) | 1 )); }
bgs1() { echo $(( $1 | 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="$(cd "$(dirname "$0")" && pwd)/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
}

read_n() { local f=$1; [[ -r "$f" ]] && tr -cd '0-9.-' <"$f" | head -c 32 || echo 0; }

say "############################################"
say "# IRON SEE · inside the box · no fold · no limit distance (SPV free)"
say "# $(date -Iseconds)"
say "############################################"
say "LAW: BGS ground · BGF measure · ESSIE hotswap · EZZIE/PHI/THERMO on BGF · SPV free never folds"

# --- secure place surface ---
say "=== SECURE PLACE (local only) ==="
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  heur_quiet=$([[ $pub -eq 0 ]] && echo 1 || echo 0)"
say "policy: UFW deny in · no 0.0.0.0 apps · WP Atomic is public site · desk stays 127"
say "always_cook pid=$(cat "$OUT/always.pid" 2>/dev/null || echo none)"

# --- TV / HDMI ---
say "=== TV / HDMI (see the sheet path) ==="
hdmi_conn=0
hdmi_name=""
hdmi_mode=""
for c in /sys/class/drm/card*-HDMI-A-*; do
  [[ -e "$c/status" ]] || continue
  st=$(cat "$c/status" 2>/dev/null || echo unknown)
  en=$(cat "$c/enabled" 2>/dev/null || echo unknown)
  modes=$(head -1 "$c/modes" 2>/dev/null || true)
  base=$(basename "$c")
  say "  $base status=$st enabled=$en mode0=${modes:-none}"
  if [[ "$st" == connected ]]; then
    hdmi_conn=1
    hdmi_name=$base
    hdmi_mode=${modes:-unknown}
  fi
done
# EDID size = presence of real sink
edid_b=0
if [[ -n "$hdmi_name" && -r "/sys/class/drm/$hdmi_name/edid" ]]; then
  edid_b=$(wc -c <"/sys/class/drm/$hdmi_name/edid" 2>/dev/null | tr -d ' ')
  say "  EDID bytes=$edid_b  (TV sink identity present · not fake)"
fi
say "BGS hdmi_live pin=$(bgs1 "$hdmi_conn")  limb=hdmi_live/"

# --- GPU · fan · power · temp (inside the RTX) ---
say "=== GPU · FAN RPM/% · POWER · TEMP (nvidia-smi) ==="
gpu_name="none"; gpu_w=0; gpu_t=0; gpu_fan=0
if command -v nvidia-smi >/dev/null 2>&1; then
  line=$(nvidia-smi --query-gpu=name,power.draw,temperature.gpu,fan.speed --format=csv,noheader,nounits 2>/dev/null | head -1 || true)
  if [[ -n "$line" ]]; then
    IFS=',' read -r gpu_name gpu_w gpu_t gpu_fan <<<"$line"
    gpu_name=$(echo "$gpu_name" | xargs)
    gpu_w=$(echo "$gpu_w" | xargs | tr -cd '0-9.'); gpu_w=${gpu_w:-0}
    gpu_t=$(echo "$gpu_t" | xargs | tr -cd '0-9.'); gpu_t=${gpu_t:-0}
    gpu_fan=$(echo "$gpu_fan" | xargs | tr -cd '0-9.'); gpu_fan=${gpu_fan:-0}
    # fan.speed is % on most drivers; true RPM needs cooler/ proprietary when exposed
    say "  name=$gpu_name"
    say "  power_W=$gpu_w  temp_C=$gpu_t  fan_pct=$gpu_fan"
    say "  BGF power_vs_temp=$(bgf "${gpu_w%.*}" "${gpu_t%.*}")  fan_vs_temp=$(bgf "${gpu_fan%.*}" "${gpu_t%.*}")"
    say "  note: fan_pct=0 at idle is normal · spin under load · chassis RPM needs SuperIO (nct/it87) if board exposes"
  fi
else
  say "  nvidia-smi missing"
fi

# --- CPU thermo / cool ---
say "=== CPU · THERMO (k10temp) ==="
cpu_t=0
for f in /sys/class/hwmon/hwmon*/temp1_input; do
  n=$(cat "$(dirname "$f")/name" 2>/dev/null || true)
  [[ "$n" == k10temp ]] || continue
  cpu_t=$(read_n "$f"); cpu_t=$((cpu_t / 1000))
  say "  Tctl≈${cpu_t}C  THERMO band=$( [[ $cpu_t -le 70 ]] && echo cool\|1 || { [[ $cpu_t -le 84 ]] && echo warm\|1 || echo hot\|1; } )"
done
# all hwmon temps short
for d in /sys/class/hwmon/hwmon*; do
  n=$(cat "$d/name" 2>/dev/null || echo ?)
  for t in "$d"/temp*_input; do
    [[ -r "$t" ]] || continue
    v=$(read_n "$t"); c=$((v/1000))
    say "  $n $(basename "$t")=${c}C"
  done
done | head -40

# --- power supply honesty ---
say "=== POWER SUPPLY (honest iron) ==="
say "  ATX PSU: no native hwmon on this board → cannot invent wall Watts"
say "  what we DO see:"
if [[ -r /sys/class/hwmon/hwmon7/power1_input ]]; then
  # amdgpu PPT microwatts
  uW=$(read_n /sys/class/hwmon/hwmon7/power1_input)
  say "  amdgpu PPT_uW=$uW  (~$(echo "scale=2; $uW/1000000" | bc 2>/dev/null || echo ?) W iGPU)"
fi
rapl_sum=0
for f in /sys/class/powercap/intel-rapl*/energy_uj /sys/class/powercap/intel-rapl*/*/energy_uj; do
  [[ -r "$f" ]] || continue
  e=$(read_n "$f")
  say "  RAPL $(echo "$f" | sed 's|.*/powercap/||') energy_uj=$e"
done
say "  GPU draw_W=$gpu_w  (board + wall ≈ GPU + package + rest · measure BGF not guess)"
say "  expansion: smart PSU (USB/HID) or inline meter → new limb psu_live/ when present"

# --- chassis fans ---
say "=== CHASSIS FANS ==="
fans=0
for f in /sys/class/hwmon/hwmon*/fan*_input; do
  [[ -r "$f" ]] || continue
  fans=$((fans+1))
  rpm=$(read_n "$f")
  n=$(cat "$(dirname "$f")/name" 2>/dev/null)
  say "  $n $(basename "$f")=${rpm} RPM"
done
if (( fans == 0 )); then
  say "  no fan*_input in hwmon · SuperIO not bound (nct6775/it87/asus-wmi)"
  say "  fix path: sensors-detect (careful) · or ASUS Armoury/EC · or PWM headers via nct"
  say "  language limb fan/ still clamps 0..255|1 · measure when sysfs appears"
  say "  GPU fan_pct=$gpu_fan is the fan we SEE now"
fi

# --- ESSIE hotswap expansion ---
say "=== ESSIE (hotswap · not EZZIE) ==="
essie_spvs=$(ls "$ROOT/RTXLayer/webbrowser/spvs"/*.js 2>/dev/null | wc -l | tr -d ' ')
say "  webbrowser SPV plugs≈$essie_spvs  · hotswap_core.py live"
say "  more ESSIE = more plugs in spvs/ · wb in <plug> · never fold into SDF field"
say "  expansion distance: free SPV channel · no length limit in law · only wire/physics"

# --- net TX/RX ---
ifc=$(awk -F: 'NR>2 {gsub(/ /,"",$1); if($1!="lo"){print $1; exit}}' /proc/net/dev)
rx=$(awk -v i="$ifc:" '$1==i{print $2;exit}' /proc/net/dev)
tx=$(awk -v i="$ifc:" '$1==i{print $10;exit}' /proc/net/dev)
say "=== NET · $ifc ==="
say "  RX=$rx TX=$tx BGF=$(bgf "$tx" "$rx") free_spv=$(spv "$tx" "$rx" "$gpu_t")"

# --- free unlimited distance metaphor + practical ---
say "=== NO FOLD · NO LIMIT DISTANCE ==="
say "  field SDF stays place · free SPV rides BGF forever (law distance unlimited)"
say "  world distance: WireGuard/SSH tunnel · never open 0.0.0.0 · still free thrift"
say "  secure places: 127 desk · WP Atomic edge · GH private · Titan mail · UFW deny in"

free_mark=$(spv "${gpu_w%.*}" "$cpu_t" "${gpu_fan%.*}")
cat >"$OUT/iron_live.json" <<JSON
{
  "ts": "$(date -Iseconds)",
  "law": "BGS → BGF(+EZZIE PHI THERMO) → SDF · ESSIE hotswap · SPV free no fold no distance limit",
  "secure": {"public_listen": $pub, "local_listen": $loc},
  "tv": {"connected": $hdmi_conn, "connector": "$hdmi_name", "mode": "$hdmi_mode", "edid_bytes": ${edid_b:-0}},
  "gpu": {"name": "$gpu_name", "power_W": $gpu_w, "temp_C": $gpu_t, "fan_pct": $gpu_fan},
  "cpu_tctl_C": $cpu_t,
  "chassis_fan_sensors": $fans,
  "essie_spv_js": $essie_spvs,
  "net": {"iface": "$ifc", "rx": $rx, "tx": $tx},
  "free_spv": $free_mark,
  "psu": "no ATX telepathy · GPU+RAPL+amdgpu PPT only until smart PSU limb",
  "log": "$LOG"
}
JSON
say "wrote $OUT/iron_live.json"
say "IRON SEE DONE · work from here · remain IN"
echo "$LOG"
