#!/bin/bash
export LC_ALL=C

# 1) watchdog should not be flagged as failed on a down probe
if ! grep -q '^SuccessExitStatus=1' /etc/systemd/system/proxylab-watchdog.service; then
  sed -i '/^Nice=10/i SuccessExitStatus=1' /etc/systemd/system/proxylab-watchdog.service
  systemctl daemon-reload
  echo "watchdog unit: SuccessExitStatus=1 added"
fi
systemctl reset-failed proxylab-watchdog.service proxy-check-stage2.service 2>/dev/null

# 2) wait for the running harvest to finish (max ~6 min)
printf '\n----- WAITING FOR HARVEST -----\n'
for i in $(seq 1 36); do
  systemctl is-active --quiet proxylab-cycle.service || break
  sleep 10
done
echo "cycle state: $(systemctl is-active proxylab-cycle.service)"

printf '\n----- CYCLE LOG (tail) -----\n'
tail -n 10 /var/log/proxylab-cycle.log 2>/dev/null

printf '\n----- HEALTHY POOL -----\n'
python3 - <<'PY'
import json
try:
    d=json.load(open('/opt/proxy-lab/data/healthy.json'))
    print('  healthy count:', len(d))
    for e in d[:8]:
        print('   - %-10s %-34s %-6s %sms exit=%s' % (e.get('type'), str(e.get('server'))[:34], e.get('port'), e.get('latency_ms'), e.get('exit_ip')))
except Exception as exc:
    print('  cannot read:', exc)
PY

printf '\n----- SERVED CONFIG -----\n'
python3 - <<'PY'
import json
c=json.load(open('/opt/proxy-lab/data/serve.json'))
for o in c['outbounds'][:-1]:
    print('  %-4s %-10s %-34s %s' % (o.get('tag'),o.get('type'),str(o.get('server'))[:34],o.get('server_port')))
print('  group:', c['outbounds'][-1]['tag'], '->', c['outbounds'][-1]['outbounds'])
PY

printf '\n----- LIVE PROBE -----\n'
for a in 127.0.0.1 172.19.0.1 172.17.0.1; do
  code=$(curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 15 -x "http://$a:20808" https://www.gstatic.com/generate_204 2>/dev/null)
  printf '  %-12s -> %s\n' "$a" "$code"
done
printf '  exit ip: '; curl -s --max-time 20 -x http://127.0.0.1:20808 https://api.ipify.org 2>/dev/null; echo

printf '\n----- UNITS -----\n'
systemctl --failed --no-pager --no-legend 2>/dev/null | head -5
systemctl is-active proxylab-serve.service proxylab-cycle.timer proxylab-watchdog.timer
