#!/usr/bin/env bash
# public + DNS truth · detect spectrum slide · stamp out/public_truth_latest.json
# LAW: public = Atomic only · 127 = employee · never auto-mutate DNS · free thrift
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
MAG="${BGRTX_MAG:-$HOME/Projects/biggrinrtx-magazine}"
mkdir -p "$OUT"
ts() { date -Iseconds; }
say() { echo "[$(ts)] $*"; }

cmd="${1:-once}"

once() {
  say "public-truth once · dig + Atomic probe"
  # prefer desk-rest when up
  if curl -fsS --max-time 2 http://127.0.0.1:18772/public >/dev/null 2>&1; then
    curl -fsS --max-time 25 http://127.0.0.1:18772/public >"$OUT/public_truth_latest.json" || true
    curl -fsS --max-time 15 http://127.0.0.1:18772/dns >"$OUT/dns_truth_latest.json" || true
  else
    python3 - <<'PY'
import json, subprocess, time, urllib.request
from pathlib import Path
OUT = Path.home() / "Projects/x/out"
OUT.mkdir(exist_ok=True)
domain = "biggrinrtx.com"

def dig(t, n):
    try:
        r = subprocess.run(["dig", "+short", t, n], capture_output=True, text=True, timeout=8)
        return [ln.strip().strip('"') for ln in r.stdout.splitlines() if ln.strip()]
    except Exception as e:
        return [f"error:{e}"]

a, mx, txt = dig("A", domain), dig("MX", domain), dig("TXT", domain)
dmarc = dig("TXT", f"_dmarc.{domain}")
spf = next((t for t in txt if "v=spf1" in t.lower()), "")
issues = []
mx_hosts = [m.split()[-1].rstrip(".").lower() for m in mx if m.split()]
for need in ("mx1.titan.email", "mx2.titan.email"):
    if not any(need in h for h in mx_hosts):
        issues.append(f"mx_missing:{need}")
for need in ("spf.titan.email", "_spf.wpcloud.com"):
    if need not in spf:
        issues.append(f"spf_missing:{need}")
if not dmarc:
    issues.append("dmarc_missing")
live = 0
title = None
try:
    req = urllib.request.Request("https://biggrinrtx.com/", headers={"User-Agent": "BGRTX-PublicTruth/1.0"})
    with urllib.request.urlopen(req, timeout=12) as r:
        live = r.status
        body = r.read(3000).decode("utf-8", errors="replace")
        import re
        m = re.search(r"<title[^>]*>([^<]+)</title>", body, re.I)
        title = m.group(1).strip()[:120] if m else None
except Exception as e:
    live = getattr(e, "code", 0) or 0
    issues.append(f"atomic_http={live}")
if live not in (200, 301, 302) and f"atomic_http={live}" not in issues:
    issues.append(f"atomic_http={live}")
stamp = {
    "ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
    "ok": len(issues) == 0,
    "issues": issues,
    "a": a, "mx": mx, "spf": spf[:200], "dmarc": dmarc[:2],
    "atomic": {"https": live, "title": title, "url": "https://biggrinrtx.com/"},
    "law": "dns truth · spectrum slide detector · no auto-mutate DNS",
}
(OUT / "public_truth_latest.json").write_text(json.dumps(stamp, indent=2))
(OUT / "dns_truth_latest.json").write_text(json.dumps({
    "ts": stamp["ts"], "ok": stamp["ok"], "issues": issues, "a": a, "mx": mx, "spf": spf[:200]
}, indent=2))
print(json.dumps({"ok": stamp["ok"], "issues": issues, "live": live}, indent=2))
PY
  fi

  # if spectrum issues — log alert only (never silent DNS rewrite)
  if [[ -f "$OUT/public_truth_latest.json" ]]; then
    python3 - <<'PY'
import json
from pathlib import Path
p = Path.home()/"Projects/x/out/public_truth_latest.json"
d = json.loads(p.read_text())
ok = d.get("ok", False)
issues = d.get("issues") or (d.get("dns") or {}).get("issues") or []
print("public_truth ok=%s issues=%s" % (ok, issues))
if not ok:
    alert = Path.home()/"Projects/x/out/PUBLIC_TRUTH_ALERT"
    alert.write_text("ALERT %s\nissues=%s\naction=check WP.com domain + Atomic · do not auto-mutate DNS\n" % (
        d.get("ts"), issues))
    print("ALERT stamped", alert)
else:
    ap = Path.home()/"Projects/x/out/PUBLIC_TRUTH_ALERT"
    if ap.is_file():
        ap.unlink()
PY
  fi

  # optional: refresh local themed primary (not a public publish)
  if [[ -x "$MAG/bin/bgrtx" ]]; then
    bash "$MAG/bin/bgrtx" local-up >>"$OUT/public-truth.log" 2>&1 || true
  fi
  say "public-truth done · see out/public_truth_latest.json"
}

case "$cmd" in
  once|check) once ;;
  status)
    [[ -f "$OUT/public_truth_latest.json" ]] && cat "$OUT/public_truth_latest.json" || echo "no stamp · run once"
    ;;
  *)
    echo "usage: $0 once|status"
    exit 2
    ;;
esac
