#!/bin/bash
# Refresh the healthy pool, measure real quality, re-render, restart if changed.
#
# Stage order matters.  The harvest (proxylab.py run) is the slow, flaky part:
# it walks hundreds of public configs and has twice sat in "chunk 1/N" for
# 15+ minutes holding the lock.  When it ran first, everything behind it --
# including the quality probe and the render -- waited, so a hung harvest left
# the pool frozen on whatever members it had before.
#
# Now the cheap, reliable stages run first against the current pool, and the
# harvest is bounded and optional.  A hung harvest can no longer stop the pool
# from being re-validated and re-rendered.
set -u
BASE=/opt/proxy-lab
LOG=/var/log/proxylab-cycle.log
LOCK=/run/proxylab-cycle.lock
PY=/usr/bin/python3
RUNUSER=/usr/sbin/runuser

exec 9>"$LOCK" || exit 0
if ! flock -n 9; then
  echo "$(date -Is) cycle: already running, skipping" >>"$LOG"
  exit 0
fi

BEFORE=$(md5sum "$BASE/data/serve.json" 2>/dev/null | awk '{print $1}')
echo "$(date -Is) cycle: start" >>"$LOG"

# 1. re-validate what we already have (fast, ~1-2 min)
timeout -k 10 600 "$RUNUSER" -u proxylab -- "$PY" "$BASE/quality_probe.py" >>"$LOG" 2>&1
qc=$?
echo "$(date -Is) cycle: quality rc=$qc" >>"$LOG"

# 2. render from measured quality
timeout -k 10 180 "$RUNUSER" -u proxylab -- "$PY" "$BASE/render.py" >>"$LOG" 2>&1
rc=$?
echo "$(date -Is) cycle: render rc=$rc" >>"$LOG"

# 3. bounded harvest of new candidates (may be skipped when it hangs)
timeout -k 15 600 "$RUNUSER" -u proxylab -- "$PY" "$BASE/proxylab.py" run >>"$LOG" 2>&1
hc=$?
echo "$(date -Is) cycle: harvest rc=$hc" >>"$LOG"

# 4. only re-probe and re-render when the harvest actually produced candidates
if [ "$hc" -eq 0 ]; then
  timeout -k 10 600 "$RUNUSER" -u proxylab -- "$PY" "$BASE/quality_probe.py" >>"$LOG" 2>&1
  echo "$(date -Is) cycle: quality(2) rc=$?" >>"$LOG"

  timeout -k 10 180 "$RUNUSER" -u proxylab -- "$PY" "$BASE/render.py" >>"$LOG" 2>&1
  rc=$?
  echo "$(date -Is) cycle: render(2) rc=$rc" >>"$LOG"
fi

AFTER=$(md5sum "$BASE/data/serve.json" 2>/dev/null | awk '{print $1}')
changed=no
[ "$BEFORE" != "$AFTER" ] && changed=yes
echo "$(date -Is) cycle: changed=$changed" >>"$LOG"

if [ "$rc" -eq 0 ] && [ "$changed" = "yes" ]; then
  systemctl restart proxylab-serve.service
  echo "$(date -Is) cycle: serve restarted" >>"$LOG"
fi

echo "$(date -Is) cycle: done" >>"$LOG"
