#!/bin/bash
# Probe every outbound in isolation: one inbound port per outbound.
export LC_ALL=C
BIN=/opt/proxy-lab/bin/sing-box
D=/tmp/qual; rm -rf "$D"; mkdir -p "$D"
PORT=22100

python3 - "$D" "$PORT" <<'PY'
import json, sys
d, port = sys.argv[1], int(sys.argv[2])
c = json.load(open('/opt/proxy-lab/data/serve.json'))
outs = [o for o in c['outbounds'] if o.get('tag') != 'auto']
cfg = {"log": {"level": "error"},
       "dns": {"servers": [{"type": "local", "tag": "local"}]},
       "inbounds": [], "outbounds": [{"type": "direct", "tag": "direct"}],
       "route": {"rules": [], "final": "direct", "default_domain_resolver": "local"}}
meta = []
for i, o in enumerate(outs):
    o = dict(o); o['tag'] = f"o{i}"
    cfg['outbounds'].append(o)
    cfg['inbounds'].append({"type": "mixed", "tag": f"in{i}", "listen": "127.0.0.1", "listen_port": port+i})
    cfg['route']['rules'].append({"inbound": [f"in{i}"], "outbound": f"o{i}"})
    meta.append({"idx": i, "port": port+i, "tag": o['tag'], "type": o.get('type'),
                 "server": o.get('server'), "sni": (o.get('tls') or {}).get('server_name')})
json.dump(cfg, open(f"{d}/probe.json", "w"))
json.dump(meta, open(f"{d}/meta.json", "w"))
print(f"  built config for {len(meta)} outbounds")
PY

$BIN run -c "$D/probe.json" >"$D/probe.log" 2>&1 &
PID=$!
sleep 4

echo
echo "  tag  type     server                  ok/N   avg    errors"
python3 - "$D" <<'PY'
import json, subprocess, sys, time
d = sys.argv[1]
meta = json.load(open(f"{d}/meta.json"))
TARGET = "https://www.gstatic.com/generate_204"
for m in meta:
    ok = 0; times = []; errs = {}
    for _ in range(5):
        t0 = time.time()
        r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                            "--max-time", "8", "-x", f"http://127.0.0.1:{m['port']}", TARGET],
                           capture_output=True, text=True)
        code = (r.stdout or "").strip()
        if code == "204":
            ok += 1; times.append(time.time() - t0)
        else:
            errs[code or "err"] = errs.get(code or "err", 0) + 1
    avg = f"{sum(times)/len(times):.2f}s" if times else "-"
    print(f"  o{m['idx']:<3} {m['type']:<8} {str(m['server'])[:22]:<22} {ok}/5   {avg:<7} {errs}")
PY

kill $PID 2>/dev/null; wait $PID 2>/dev/null
echo
echo "  (log) $(grep -icE 'error' "$D/probe.log") error lines"
