#!/bin/bash
export LC_ALL=C
printf '\n----- WAITING FOR HARVEST TO FINISH -----\n'
for i in $(seq 1 40); do
  st=$(systemctl is-active proxylab-cycle.service 2>/dev/null)
  case "$st" in
    activating|active) sleep 15 ;;
    *) break ;;
  esac
done
printf 'final cycle state: %s\n' "$(systemctl is-active proxylab-cycle.service 2>/dev/null)"

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

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

printf '\n----- SERVED OUTBOUNDS -----\n'
python3 - <<'PY'
import json
c=json.load(open('/opt/proxy-lab/data/serve.json'))
for o in c['outbounds'][:-1]:
    print('  %-4s %-9s %-32s %s' % (o.get('tag'),o.get('type'),str(o.get('server'))[:32],o.get('server_port')))
print('  group auto ->', 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----- SERVICE HEALTH -----\n'
systemctl is-active proxylab-serve.service; systemctl show proxylab-serve.service -p NRestarts --value
systemctl --failed --no-pager --no-legend 2>/dev/null | head -4
