#!/bin/bash
# Keep the local proxy endpoint alive AND actually usable.
#
# The old watchdog only asked gstatic/204.  A worker proxy can answer that and
# still fail OpenRouter or Google Generative Language, which is exactly the
# "Connection error" the apps saw while the watchdog reported "recovered".
#
#   1. probe base + OpenRouter through the endpoint; healthy -> exit
#   2. restart serve (rate limited)
#   3. re-render from the measured pool and restart
#   4. if the pool is empty -> trigger a fresh harvest (max once / 30 min)
set -u
LOG=/var/log/proxylab-watchdog.log
PORT=20808
BASE_URL=https://www.gstatic.com/generate_204
OR_URL=https://openrouter.ai/api/v1/models
PY=/usr/bin/python3
RUNUSER=/usr/sbin/runuser
RESTART_STAMP=/run/proxylab-serve-restart.stamp
REFRESH_STAMP=/run/proxylab-refresh.stamp

log() { echo "$(date -Is) $*" >>"$LOG"; }

code() {
  curl -s -o /dev/null -w '%{http_code}' --max-time 8 -x "http://127.0.0.1:$PORT" "$1" 2>/dev/null
}

check() {
  local b o
  b=$(code "$BASE_URL")
  if [ "$b" != "204" ]; then echo "base=$b"; return 1; fi
  o=$(code "$OR_URL")
  case "$o" in
    200|401) return 0 ;;
    *) echo "openrouter=$o"; return 1 ;;
  esac
}

restart_serve() {
  now=$(date +%s); last=0
  [ -f "$RESTART_STAMP" ] && last=$(stat -c %Y "$RESTART_STAMP")
  if [ $((now - last)) -lt 180 ]; then
    log "serve restart skipped (last restart $((now - last))s ago)"
    return 1
  fi
  touch "$RESTART_STAMP"
  systemctl restart proxylab-serve.service
  log "serve restarted"
  return 0
}

why=$(check) && exit 0
sleep 3
why=$(check) && exit 0
log "probe failed ($why)"

if restart_serve; then
  sleep 6
  why=$(check) && { log "recovered after restart"; exit 0; }
  log "still down after restart ($why)"
fi

"$RUNUSER" -u proxylab -- "$PY" /opt/proxy-lab/render.py >>"$LOG" 2>&1
if [ $? -eq 0 ]; then
  systemctl restart proxylab-serve.service
  sleep 6
  why=$(check) && { log "recovered after re-render"; exit 0; }
  log "still down after re-render ($why)"
fi

now=$(date +%s); last=0
[ -f "$REFRESH_STAMP" ] && last=$(stat -c %Y "$REFRESH_STAMP")
if [ $((now - last)) -ge 1800 ]; then
  touch "$REFRESH_STAMP"
  systemctl start --no-block proxylab-cycle.service
  log "triggered fresh harvest cycle"
else
  log "pool refresh skipped (last refresh $((now - last))s ago)"
fi
exit 1
