#!/usr/bin/env bash
# scripts/fda-grant-review — advisory 30-day cadence nudge for the macOS
# Full-Disk-Access grant + brew-pin drift audit. Mirrors token-review /
# gripe-gc-review / skill-search-review: it does NOT do the audit (that's a
# per-host check — see the runbook), it only tells you WHEN one is due, plus a
# best-effort count of any live nas-denied alerts. Surfaced in
# `/whatneedsdoing`; always exits 0.
#
# Why this exists: macOS 15+ denies NFS access to every launchd/cron process
# unless its interpreter has Full Disk Access, and the grant is pinned to the
# binary's cdhash — so `brew upgrade python@3.1x` silently breaks it and every
# daemon EPERMs on /opt/nas (the 2026-07 melchior lockout, dark for days). The
# nursery `nas-denied` detector is the real-time backstop (alerts in minutes);
# this pass is the slow, proactive drift audit: are all Macs' *currently-
# resolved* daemon interpreters still granted (auth_value=2) and pinned?
# Procedure + dated log:
#   docs/runbooks/fda-grant-review.md   (the `## Log` section is the clock)
set -euo pipefail
cd "$(dirname "$0")/.."

LOG="docs/runbooks/fda-grant-review.md"
WINDOW_DAYS=30

if [[ ! -f "$LOG" ]]; then
    echo "fda-grant-review: DUE (no runbook at $LOG)"; exit 0
fi

# newest dated line in the `## Log` section (any order — sort -r picks the newest date)
last=$(awk '/^## Log/{f=1;next} f' "$LOG" \
    | grep -oE '\*\*[0-9]{4}-[0-9]{2}-[0-9]{2}\*\*' | sort -r | head -1 | tr -d '*' || true)

if [[ -z "$last" ]]; then
    echo "fda-grant-review: DUE (no dated entry in $LOG '## Log')"; exit 0
fi

# portable YYYY-MM-DD -> epoch seconds (BSD date on macOS, GNU date on CI/Linux)
epoch_of() { date -u -j -f "%Y-%m-%d" "$1" +%s 2>/dev/null || date -u -d "$1" +%s 2>/dev/null; }
last_e=$(epoch_of "$last" || true)
now_e=$(date +%s)

if [[ -z "$last_e" ]]; then
    echo "fda-grant-review: last entry '$last' unparseable — check $LOG"; exit 0
fi

days=$(( (now_e - last_e) / 86400 ))
if (( days > WINDOW_DAYS )); then
    echo "fda-grant-review: DUE (last pass $last, ${days}d ago > ${WINDOW_DAYS}d) — audit each Mac's resolved daemon interpreters for FDA (auth_value=2) + brew-pin, re-grant/pin any drift, append a dated line to $LOG. See the runbook."
    # Best-effort nicety: any live nas-denied alerts right now? Never blocks or
    # fails the clock — guarded with || true throughout.
    open=$(scripts/prod-psql "SELECT count(*) FROM refs WHERE kind='alert' AND alert_source='nursery:nas-denied' AND resolved_at IS NULL;" 2>/dev/null | tr -d '[:space:]' || true)
    if [[ -n "$open" && "$open" =~ ^[0-9]+$ ]]; then
        if (( open > 0 )); then
            echo "  ⚠ $open OPEN nas-denied alert(s) in prod NOW — a Mac is actively locked out; fix before the audit."
        else
            echo "  (0 open nas-denied alerts — no host is currently locked out)"
        fi
    fi
else
    echo "fda-grant-review: ok (last pass $last, ${days}d ago; due in $(( WINDOW_DAYS - days ))d)"
fi
exit 0
