#!/bin/bash
export LC_ALL=C
BIN=/opt/proxy-lab/bin/sing-box
D=/tmp/sbtest; mkdir -p "$D"
DOH="https://cloudflare-dns.com/dns-query"

echo "===== 1) DNS IS POISONED? (system resolver vs DoH) ====="
for h in lucasjow.us.ci snip.edgeoneai.cc.cd; do
  printf '  %-24s system=%s\n' "$h" "$(getent ahostsv4 "$h" 2>/dev/null | awk '{print $1}' | head -1)"
  printf '  %-24s DoH   =%s\n' "" "$(curl -s --max-time 10 -H 'accept: application/dns-json' "$DOH?name=$h&type=A" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(" ".join(a["data"] for a in d.get("Answer",[])[:3]) or "-")' 2>/dev/null)"
done

echo
echo "===== 2) FETCH ECH CONFIG VIA DoH ====="
python3 - <<'PY'
import json,urllib.request,base64
doh="https://cloudflare-dns.com/dns-query"
out={}
for host in ["lucasjow.us.ci","snip.edgeoneai.cc.cd","www.volumeroot.com"]:
    try:
        req=urllib.request.Request(f"{doh}?name={host}&type=HTTPS",headers={"accept":"application/dns-json"})
        d=json.load(urllib.request.urlopen(req,timeout=10))
        ech=None
        for a in d.get("Answer",[]):
            for tok in a.get("data","").split():
                if tok.startswith("ech="):
                    ech=tok[4:]
        print(f"  {host:24s} ech={'found len '+str(len(ech)) if ech else 'NONE'}")
        if ech:
            pad="="*(-len(ech)%4)
            raw=base64.urlsafe_b64decode(ech+pad)
            out[host]=base64.b64encode(raw).decode()
    except Exception as e:
        print(f"  {host:24s} error {e}")
json.dump(out,open("/tmp/sbtest/ech_configs.json","w"))
print("  saved:",", ".join(out.keys()) or "none")
PY

echo
echo "===== 3) SING-BOX WITH REAL ECHConfigList ====="
python3 - <<'PY'
import json
cfg=json.load(open("/tmp/sbtest/ech_configs.json"))
host="lucasjow.us.ci"
ech=cfg.get(host)
if not ech:
    raise SystemExit("no ech config for "+host)
c={
 "log":{"level":"warn"},
 "inbounds":[{"type":"mixed","tag":"in","listen":"127.0.0.1","listen_port":21999}],
 "outbounds":[{
   "type":"vless","tag":"p","server":"188.114.97.6","server_port":443,
   "uuid":"e6df2095-a73c-4043-8693-8d5a03686870",
   "tls":{"enabled":True,"server_name":host,"alpn":["http/1.1"],
          "utls":{"enabled":True,"fingerprint":"chrome"},
          "ech":{"enabled":True,"config":ech}},
   "transport":{"type":"ws","path":"/","headers":{"Host":host}}}],
 "route":{"final":"p"}
}
json.dump(c,open("/tmp/sbtest/realech.json","w"),indent=1)
print("  wrote config")
PY

printf '  check: '
if $BIN check -c "$D/realech.json" 2>"$D/realech.check"; then echo OK; else echo "FAIL: $(head -2 "$D/realech.check")"; fi

if $BIN check -c "$D/realech.json" >/dev/null 2>&1; then
  $BIN run -c "$D/realech.json" >"$D/realech.log" 2>&1 &
  pid=$!; sleep 3
  code=$(curl -s -o /dev/null -w '%{http_code} %{time_total}s' --max-time 15 -x http://127.0.0.1:21999 https://www.gstatic.com/generate_204 2>/dev/null)
  echo "  PROBE -> $code"
  echo "  exit ip -> $(curl -s --max-time 15 -x http://127.0.0.1:21999 https://api.ipify.org 2>/dev/null)"
  kill $pid 2>/dev/null; wait $pid 2>/dev/null
  echo "  log: $(tail -2 "$D/realech.log" | tr '\n' ' ' | cut -c1-200)"
fi
