#!/usr/bin/env bash
# adom-digikey watchdog — app-local, cron every 2 min.
# Responsibilities:
#   1. Keep /health green (relaunch if down).
#   2. Auto-deploy: if origin/main has moved, pull + rebuild + restart.
# No gallia dependency. Run from $REPO_DIR/service/watchdog.sh.

set -euo pipefail
set -a; [ -f /etc/environment ] && . /etc/environment; set +a

PORT="${DIGIKEY_PORT:-8777}"
LOG=/tmp/adom-digikey.log
REPO_DIR="${ADOM_DIGIKEY_REPO:-$HOME/adom-digikey}"
BIN=/usr/local/bin/adom-digikey

# ── 1. Self-update (pull + rebuild + reinstall) ────────────────────
if [ -d "$REPO_DIR/.git" ]; then
  cd "$REPO_DIR"
  local_sha=$(git rev-parse HEAD 2>/dev/null || echo "")
  if git fetch --quiet origin main 2>/dev/null; then
    remote_sha=$(git rev-parse origin/main 2>/dev/null || echo "")
    if [ -n "$remote_sha" ] && [ "$local_sha" != "$remote_sha" ]; then
      echo "[$(date -Iseconds)] watchdog: updating $local_sha -> $remote_sha" >> "$LOG"
      git reset --hard origin/main >> "$LOG" 2>&1
      # cargo build may take a while; keep the old binary running until the new one builds
      if [ -f "$HOME/.cargo/env" ]; then . "$HOME/.cargo/env"; fi
      if cargo build --release >> "$LOG" 2>&1; then
        sudo install -m 0755 "$REPO_DIR/target/release/adom-digikey" "$BIN"
        pkill -f 'adom-digikey serve' 2>/dev/null || true
        echo "[$(date -Iseconds)] watchdog: rebuilt + swapped" >> "$LOG"
      else
        echo "[$(date -Iseconds)] watchdog: BUILD FAILED for $remote_sha; keeping old binary" >> "$LOG"
      fi
    fi
  fi
fi

# ── 2. Liveness check + relaunch ───────────────────────────────────
# "Liveness" here = the service is accepting connections. We do NOT treat
# HTTP 500 as unhealthy because the service legitimately 500s on /health
# when DIGIKEY_CLIENT_ID isn't set (= misconfigured, not dead). Restarting it
# wouldn't fix a missing env var; it would just thrash.
# `curl -s` (without -f) returns 0 for any HTTP response, non-zero only
# when it can't connect at all.
if curl -s --max-time 3 "http://127.0.0.1:$PORT/health" -o /dev/null; then
  exit 0  # service is listening; leave it alone
fi

echo "[$(date -Iseconds)] watchdog: port $PORT not accepting, (re)launching" >> "$LOG"
pkill -f 'adom-digikey serve' 2>/dev/null || true
sleep 1
nohup "$BIN" serve --port "$PORT" >> "$LOG" 2>&1 &
disown || true

# Give it a moment then verify it's accepting.
sleep 3
if curl -s --max-time 3 "http://127.0.0.1:$PORT/health" -o /dev/null; then
  echo "[$(date -Iseconds)] watchdog: relaunch OK (listening)" >> "$LOG"
else
  echo "[$(date -Iseconds)] watchdog: relaunch FAILED (port still closed)" >> "$LOG"
  exit 1
fi
