#!/usr/bin/env bash
# adom-courier watchdog — cron every 2 min.
# Update model = the wiki.adom.inc REGISTRY via the adom-wiki CLI. adom-courier is a PUBLIC
# package, so the pull needs no auth at all — no git, no api-key. `adom-wiki pkg publish` a new
# version → this pulls it (≤15-min cadence) → restarts. Config/state live in ~/.config/adom-courier
# so the package re-extract never clobbers them. Scoped full-path kills, never `pkill node`.
set -uo pipefail
export PATH="$HOME/.local/bin:/usr/local/bin:$PATH"
PKG_DIR="${ADOM_COURIER_PKG:-$HOME/project/adom_modules/adom/adom-courier}"
PORT="${PORT:-8870}"; LOG="/tmp/adom-courier.log"
export HOST="${HOST:-0.0.0.0}" PORT
DATA="$HOME/.config/adom-courier"; MARK="$DATA/.server-mtime"; UMARK="$DATA/.last-update"
mkdir -p "$DATA"

start(){ cd "$PKG_DIR" && nohup /usr/bin/node "$PKG_DIR/server.js" >> "$LOG" 2>&1 & disown; }
mtime(){ stat -c %Y "$PKG_DIR/server.js" 2>/dev/null || echo 0; }

# 1. pull published updates from the registry — at most every ~15 min (cheap version check)
now=$(date +%s); last=$(cat "$UMARK" 2>/dev/null || echo 0)
if [ $((now - last)) -ge 900 ]; then
  adom-wiki pkg update adom/adom-courier >> "$LOG" 2>&1 || true
  echo "$now" > "$UMARK"
fi

# 2. (re)start if the package changed (update pulled a new server.js) or it's down
m=$(mtime); was=$(cat "$MARK" 2>/dev/null || echo 0)
if [ "$m" != "$was" ] || ! curl -sf --max-time 3 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then
  echo "[$(date -Iseconds)] watchdog: (re)starting (server.js mtime $was -> $m)" >> "$LOG"
  pkill -f "$PKG_DIR/server.js" 2>/dev/null || true; sleep 1; start
  echo "$m" > "$MARK"
fi