#!/bin/bash
# Keep the local proxy endpoint alive.
#  1. probe through the proxy; if healthy -> exit
#  2. restart serve (rate-limited)
#  3. re-render from the pool and restart
#  4. if the pool itself is dead -> trigger a fresh harvest (max once / 30 min)
set -u
LOG=/var/log/proxylab-watchdog.log
PORT=20808
URL=https://www.gstatic.com/generate_204
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"; }

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

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
}

code=$(probe)
[ "$code" = "204" ] && exit 0
sleep 3
code=$(probe)
[ "$code" = "204" ] && exit 0

log "probe failed (http=$code)"

if restart_serve; then
  sleep 6
  code=$(probe)
  [ "$code" = "204" ] && { log "recovered after restart"; exit 0; }
  log "still down after restart (http=$code)"
fi

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

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