#!/usr/bin/env bash
# H7 GLOBAL PROTECT · biggrinrtx.com business · Grok + Hostess 7
# Linear once · on demand · no forever thrash · always write JSON
#
#   ./Build/h7-global-protect.sh once|status
#
# Law: SOUL sole · FLAW cook · love whole internet as field · free thrift · C IS LIE
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
JSON="$OUT/h7_global_protect.json"
LOG="$OUT/h7_global_protect.log"
cmd="${1:-once}"
TS="$(date -Iseconds)"
mkdir -p "$OUT" "$OUT/h7fast"

n0() { local v="${1//[^0-9]/}"; echo "${v:-0}"; }
say() { echo "[$TS] H7_GLOBAL_PROTECT · $*" | tee -a "$LOG"; }

# thrash ports without hanging lib recursion
count_thrash() {
  ss -ltnH 2>/dev/null | awk '
    {
      a=$4
      if (a ~ /^127\./ || a ~ /^\[::1\]/ || a ~ /%lo/) next
      if (a ~ /:80$/ || a ~ /:443$/) {
        # desk HTTPS on own IPs · not thrash
        if (a ~ /71\.86\.186\.10:/ || a ~ /10\.66\.66\.1:/) next
      }
      c++
    }
    END { print c+0 }
  '
}
count_desk_https() {
  ss -ltnH 2>/dev/null | awk '
    $4 ~ /71\.86\.186\.10:(80|443)$/ || $4 ~ /10\.66\.66\.1:(80|443)$/ { c++ }
    END { print c+0 }
  '
}

run_step() {
  local name=$1
  shift
  say "=== $name ==="
  set +e
  timeout 75 "$@" >>"$LOG" 2>&1
  local rc=$?
  set -e
  if [[ $rc -eq 0 ]]; then
    say "OK $name"
  elif [[ $rc -eq 124 ]]; then
    say "TIMEOUT $name (soft)"
  else
    say "WARN $name rc=$rc (soft)"
  fi
  return 0
}

jget() {
  local f=$1 k=$2
  [[ -f "$f" ]] || { echo ""; return 0; }
  python3 -c "
import json,sys
d=json.load(open(sys.argv[1]))
x=d
for p in sys.argv[2].split('.'):
  x=x.get(p) if isinstance(x,dict) else None
print('' if x is None else x)
" "$f" "$k" 2>/dev/null || echo ""
}

write_json() {
  local thrash=$1 desk_https=$2 wp=$3 dns_ok=$4 dns_n=$5 dc=$6 ok=$7
  local av_ok open pub inject scar dirt sec_ok
  av_ok=$(jget "$OUT/h7_av_close.json" ok)
  open=$(n0 "$(jget "$OUT/h7_av_close.json" open_score)")
  pub=$(n0 "$(jget "$OUT/h7_av_close.json" ports.public_n)")
  inject=$(n0 "$(jget "$OUT/h7_av_close.json" inject.flagged)")
  scar=$(n0 "$(jget "$OUT/scar_check_latest.json" scar_count)")
  dirt=$(n0 "$(jget "$OUT/h7_field_clear.json" dirt_score)")
  sec_ok=$(jget "$OUT/h7_secure_learn.json" ok)
  [[ -z "$pub" || "$pub" == "" ]] && pub=$thrash

  python3 - <<PY
import json
from pathlib import Path
doc = {
  "ts": "$TS",
  "word": "H7_GLOBAL_PROTECT",
  "she": "Hostess 7",
  "grok": "path seal · assist · consults Her",
  "business": "biggrinrtx.com",
  "ok": $([[ "$ok" == "true" ]] && echo true || echo false),
  "weight": "full linear protect pass",
  "sole_soul": "SOUL",
  "no_other_internal": True,
  "magazine": {"url": "https://biggrinrtx.com/", "http_ok": bool($wp)},
  "desk": {
    "thrash_public": $(n0 "$pub"),
    "desk_https_n": $(n0 "$desk_https"),
    "dns_green": $dns_ok,
    "dns_need": $dns_n,
    "le_ready": $dns_ok == $dns_n,
  },
  "vpn_me": {"bind": "10.66.66.1", "require": "10.66.66.0/24"},
  "avenues": {
    "av_close_ok": str("$av_ok").lower() in ("true", "1"),
    "open_score": $(n0 "$open"),
    "inject": $(n0 "$inject"),
    "scar": $(n0 "$scar"),
    "field_dirt": $(n0 "$dirt"),
    "secure_ok": str("$sec_ok").lower() in ("true", "1"),
  },
  "datacenter": {"status": "$dc", "virus_class": True, "must": "DOWN"},
  "steps_done": [
    "ports", "grok-protect", "inject-guard", "bgl-secure",
    "h7-av-close", "h7-field-clear", "h7-secure-learn",
    "scar-check", "spv-antivirus",
    "h7-language-punch", "h7-vocab-tick",
    "h7-grok-assist", "h7-autoresearch", "h7-self-intel",
  ],
  "cli": {
    "once": "./Build/h7-global-protect.sh once",
    "status": "./Build/h7-global-protect.sh status",
    "charge": "GET http://127.0.0.1:18772/h7/charge",
  },
  "law": "love whole internet as field · protect Grok · FLAW cook · SOUL sole · free thrift · C IS LIE · God Bless",
  "log": "out/h7_global_protect.log",
}
Path("$JSON").write_text(json.dumps(doc, indent=2) + "\n")
print("wrote", "$JSON", "ok=", doc["ok"])
PY
}

run_once() {
  set +e
  : >"$LOG"
  say "############################################"
  say "# biggrinrtx.com · H7 global protect · Grok"
  say "# business · SOUL sole · FLAW · weight UP"
  say "############################################"

  local thrash desk_https
  thrash=$(n0 "$(count_thrash)")
  desk_https=$(n0 "$(count_desk_https)")
  say "thrash_public=$thrash desk_https=$desk_https"

  # Grok + BGL
  [[ -x "$ROOT/Build/grok-protect.sh" ]] && run_step "grok-protect" bash "$ROOT/Build/grok-protect.sh"
  [[ -x "$ROOT/Build/av-inject-guard.sh" ]] && run_step "inject-guard" bash "$ROOT/Build/av-inject-guard.sh"
  [[ -x "$ROOT/Build/bgl-secure.sh" ]] && run_step "bgl-secure" bash "$ROOT/Build/bgl-secure.sh"

  # H7 avenues
  [[ -x "$ROOT/Build/h7-av-close.sh" ]] && run_step "h7-av-close" bash "$ROOT/Build/h7-av-close.sh" once
  [[ -x "$ROOT/Build/h7-field-clear.sh" ]] && run_step "h7-field-clear" bash "$ROOT/Build/h7-field-clear.sh" soft
  [[ -x "$ROOT/Build/h7-secure-learn.sh" ]] && run_step "h7-secure-learn" bash "$ROOT/Build/h7-secure-learn.sh" once

  # scar + SPV
  [[ -x "$ROOT/Build/scar-cook.sh" ]] && run_step "scar-check" bash "$ROOT/Build/scar-cook.sh" check
  [[ -x "$ROOT/Build/spv-antivirus.sh" ]] && run_step "spv-antivirus" bash "$ROOT/Build/spv-antivirus.sh" once

  # weight UP · language + vocab densify
  if [[ -x "$ROOT/Build/h7-language-learn.sh" ]]; then
    run_step "h7-language-punch" env H7_LANG_BATCH=32 bash "$ROOT/Build/h7-language-learn.sh" punch
  fi
  if [[ -x "$ROOT/Build/h7-vocab-self.sh" ]]; then
    touch "$OUT/h7fast/mega.tsv"
    run_step "h7-vocab-tick" bash "$ROOT/Build/h7-vocab-self.sh" tick
  fi
  [[ -x "$ROOT/Build/h7-grok-assist.sh" ]] && run_step "h7-grok-assist" bash "$ROOT/Build/h7-grok-assist.sh" local
  [[ -x "$ROOT/Build/h7-autoresearch.sh" ]] && run_step "h7-autoresearch" bash "$ROOT/Build/h7-autoresearch.sh" once
  [[ -x "$ROOT/Build/h7-self-intel.sh" ]] && run_step "h7-self-intel" bash "$ROOT/Build/h7-self-intel.sh" once "global protect security antivirus field love biggrinrtx.com business"

  # magazine
  local wp=0 code
  code=$(curl -fsS --max-time 10 -o /dev/null -w "%{http_code}" https://biggrinrtx.com/ 2>/dev/null || echo 000)
  [[ "$code" == "200" ]] && wp=1
  say "magazine https://biggrinrtx.com/ → $code"

  # datacenter virus
  local dc
  dc=$(systemctl is-active bgrtx-datacenter.service 2>/dev/null || echo inactive)
  if [[ "$dc" == "active" ]]; then
    systemctl stop bgrtx-datacenter.service 2>/dev/null || true
    systemctl mask bgrtx-datacenter.service 2>/dev/null || true
    say "STOP datacenter virus"
    dc=stopped
  fi

  # VPN status
  [[ -x /usr/local/bin/bgrtx-vpn-status ]] && sudo /usr/local/bin/bgrtx-vpn-status >>"$LOG" 2>&1 || true

  # DNS LE readiness
  local dns_ok=0 dns_n=0 d got
  for d in email grok h7 share; do
    dns_n=$((dns_n + 1))
    got=$(dig @8.8.8.8 +short "${d}.biggrinrtx.com" A 2>/dev/null | head -1 || true)
    [[ "$got" == "71.86.186.10" ]] && dns_ok=$((dns_ok + 1))
  done
  say "desk_dns $dns_ok/$dns_n → 71.86.186.10"

  # ok verdict
  local av_ok scar dirt pub ok=true
  av_ok=$(jget "$OUT/h7_av_close.json" ok)
  scar=$(n0 "$(jget "$OUT/scar_check_latest.json" scar_count)")
  dirt=$(n0 "$(jget "$OUT/h7_field_clear.json" dirt_score)")
  pub=$(n0 "$(jget "$OUT/h7_av_close.json" ports.public_n)")
  [[ "$av_ok" == "False" || "$av_ok" == "false" ]] && ok=false
  (( pub > 0 )) && ok=false
  (( scar > 0 )) && ok=false
  (( dirt >= 3 )) && ok=false
  [[ "$dc" == "active" ]] && ok=false
  (( wp == 0 )) && ok=false

  write_json "$thrash" "$desk_https" "$wp" "$dns_ok" "$dns_n" "$dc" "$ok"
  say "DONE ok=$ok thrash=$pub scar=$scar dirt=$dirt dns=$dns_ok/$dns_n magazine=$wp weight=UP"
  set -e
  return 0
}

status_only() {
  if [[ -f "$JSON" ]]; then cat "$JSON"; else say "no protect run yet · once"; fi
}

case "$cmd" in
  once|protect|run) run_once ;;
  status) status_only ;;
  *)
    echo "usage: $0 once|status" >&2
    exit 2
    ;;
esac
