#!/usr/bin/env bash
# gateway-watchdog-vps.sh — alert-only watchdog for the VPS gateway.
#
# Cron contract (no_agent delivery): EMPTY stdout = silent. Non-empty stdout
# = Rob gets a Telegram message. So:
#   - healthy                       -> silent
#   - down inside planned window    -> silent (03:00-03:10 UTC refresh bounce)
#   - down unexpectedly, 1st detect -> print alert (once, until resolved)
#   - back up after an alert        -> print resolved (once)
#
# systemd (Restart=on-failure) owns restarts; this script never restarts
# anything — it only tells Rob when reality diverges from plan.
set -uo pipefail

STATE="/root/.hermes/logs/gateway-watchdog.state"   # "up" | "down"
LOG="/root/.hermes/logs/gateway-watchdog.log"

now_min=$(date -u +%H%M)     # e.g. 0305
now_min=${now_min#0}         # strip leading zero for arithmetic-ish compare

in_window() {
  # Planned maintenance: 03:00-03:10 UTC (gbrain-refresh cron bounces gateway)
  [ "$now_min" -ge 300 ] && [ "$now_min" -le 310 ]
}

is_active() {
  systemctl is-active --quiet hermes-gateway.service
}

prev="up"
[ -f "$STATE" ] && prev=$(cat "$STATE" 2>/dev/null || echo up)

ts() { date -u +%Y-%m-%dT%H:%M:%SZ; }

if is_active; then
  if [ "$prev" = "down" ]; then
    echo "✅ Gateway is back up ($(ts) UTC)."
    echo "up" > "$STATE"
    echo "[$(ts)] resolved: gateway active again" >> "$LOG"
  fi
  exit 0
fi

# gateway is NOT active
if in_window; then
  # expected — refresh cron owns this window
  exit 0
fi

if [ "$prev" != "down" ]; then
  echo "down" > "$STATE"
  echo "[$(ts)] ALERT: gateway inactive outside maintenance window" >> "$LOG"
  # Report what systemd sees so Rob gets context in the same message
  status=$(systemctl is-active hermes-gateway.service 2>&1)
  lastlog=$(journalctl -u hermes-gateway -n 3 --no-pager 2>/dev/null | tail -3)
  printf "🚨 Gateway is DOWN outside the planned window ($(ts) UTC).\nsystemctl says: %s\nLast log lines:\n%s\nsystemd should auto-restart it — I'll confirm when it's back.\n" "$status" "$lastlog"
fi
exit 0
