#!/bin/bash
# Watch public DNS for desk A records · when all point to this box, issue legal LE certs.
# Stack: ASM + HTML5/JS/CSS + WordPress · hugely legit.
set -euo pipefail
IP_EXPECT="${DESK_IP:-71.86.186.10}"
DOMAINS=(email.biggrinrtx.com grok.biggrinrtx.com h7.biggrinrtx.com share.biggrinrtx.com)
LOG="${LOG:-/home/default/Projects/x/out/legit-dns-watch.log}"
mkdir -p "$(dirname "$LOG")"
echo "[$(date -Is)] watch start · expect A=$IP_EXPECT" | tee -a "$LOG"

need() {
  local d="$1"
  local got
  got=$(dig @8.8.8.8 +short "$d" A | head -1 || true)
  [[ "$got" == "$IP_EXPECT" ]]
}

while true; do
  ok=1
  line="[$(date -Is)]"
  for d in "${DOMAINS[@]}"; do
    got=$(dig @8.8.8.8 +short "$d" A | head -1 || true)
    line+=" ${d##*.biggrinrtx.com}${d%%.*}=${got:-none}"
    # simpler:
    :
  done
  # recompute clean
  line="[$(date -Is)]"
  for d in "${DOMAINS[@]}"; do
    got=$(dig @8.8.8.8 +short "$d" A | head -1 || true)
    short="${d%%.*}"
    line+=" $short=${got:-∅}"
    if [[ "$got" != "$IP_EXPECT" ]]; then ok=0; fi
  done
  echo "$line ok=$ok" | tee -a "$LOG"
  if [[ "$ok" -eq 1 ]]; then
    echo "[$(date -Is)] DNS ready · running bgrtx-certbot-desk" | tee -a "$LOG"
    if sudo /usr/local/bin/bgrtx-certbot-desk >>"$LOG" 2>&1; then
      echo "[$(date -Is)] LEGAL CERT LIVE" | tee -a "$LOG"
      exit 0
    else
      echo "[$(date -Is)] certbot failed · retry in 120s" | tee -a "$LOG"
      sleep 120
      continue
    fi
  fi
  sleep 60
done
