#!/usr/bin/env bash
# adom-jlcpcb watchdog — app-local, cron every 2 min.
# Responsibilities:
#   1. Keep the Node /health green (relaunch Node if down).
#   2. Auto-deploy: if origin/main has moved, pull + npm install + restart.
# No gallia dependency. No Rust backend — this watches the Node server.

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

PORT="${JLCPCB_PORT:-8774}"
LOG=/tmp/adom-jlcpcb-server.log
REPO_DIR="${ADOM_JLCPCB_REPO:-$HOME/adom-jlcpcb}"
BACKEND_DIR="$REPO_DIR/service/backend"

# ── 1. Self-update (pull + npm install if deps changed + restart) ──
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
      # If service/backend/package.json changed since last run, reinstall deps.
      if git diff --name-only "$local_sha" "$remote_sha" 2>/dev/null | grep -q 'service/backend/package'; then
        (cd "$BACKEND_DIR" && npm install --no-audit --no-fund --omit=dev >> "$LOG" 2>&1)
      fi
      # Optional: rebuild Rust CLI if src/ changed
      if command -v cargo >/dev/null && git diff --name-only "$local_sha" "$remote_sha" 2>/dev/null | grep -qE '^(src/|Cargo)'; then
        (cd "$REPO_DIR" && cargo build --release >> "$LOG" 2>&1 && \
          sudo install -m 0755 target/release/adom-jlcpcb /usr/local/bin/adom-jlcpcb) || true
      fi
      # Trigger Node server restart to pick up new server.js
      pkill -f 'node.*service/backend/server.js' 2>/dev/null || true
      echo "[$(date -Iseconds)] watchdog: updated + restarting Node" >> "$LOG"
    fi
  fi
fi

# ── 2. Liveness check ──────────────────────────────────────────────
if curl -s --max-time 3 "http://127.0.0.1:$PORT/health" -o /dev/null; then
  exit 0  # listening; leave alone
fi

echo "[$(date -Iseconds)] watchdog: port $PORT not accepting, (re)launching Node server" >> "$LOG"
pkill -f 'node.*service/backend/server.js' 2>/dev/null || true
sleep 1
cd "$BACKEND_DIR"
export JLCPCB_DB_PATH="$BACKEND_DIR/jlcpcb-components.sqlite3"
nohup node server.js >> "$LOG" 2>&1 &
disown || true

sleep 3
if curl -s --max-time 3 "http://127.0.0.1:$PORT/health" -o /dev/null; then
  echo "[$(date -Iseconds)] watchdog: Node relaunch OK" >> "$LOG"
else
  echo "[$(date -Iseconds)] watchdog: Node relaunch FAILED" >> "$LOG"
  exit 1
fi