#!/bin/bash
export LC_ALL=C
BIN=/opt/proxy-lab/bin/sing-box
D=/tmp/sbtest
mkdir -p "$D"

UUID=495c7195-85b8-498a-bf20-2ea9ce9175b5
SNI=snip.edgeoneai.cc.cd
IP=188.114.98.0

mkcfg() {  # $1=file $2=ech-json(or empty)
cat > "$1" <<EOF
{
  "log": {"level": "warn"},
  "inbounds": [{"type": "mixed", "tag": "in", "listen": "127.0.0.1", "listen_port": 21999}],
  "outbounds": [{
    "type": "vless", "tag": "p", "server": "$IP", "server_port": 443, "uuid": "$UUID",
    "tls": {"enabled": true, "server_name": "$SNI", "alpn": ["http/1.1"],
            "utls": {"enabled": true, "fingerprint": "chrome"}$2},
    "transport": {"type": "ws", "path": "/", "headers": {"Host": "$SNI"}}
  }],
  "route": {"final": "p"}
}
EOF
}

mkcfg "$D/noech.json" ""
mkcfg "$D/ech.json" ',
            "ech": {"enabled": true, "config": "cloudflare-ech.com+udp://1.1.1.1"}'

printf '\n----- CONFIG CHECK -----\n'
for f in noech ech; do
  printf '%-6s ' "$f"
  if $BIN check -c "$D/$f.json" >"$D/$f.check" 2>&1; then echo OK; else echo "FAIL: $(head -2 "$D/$f.check")"; fi
done

run_test() {
  local name=$1
  $BIN run -c "$D/$name.json" >"$D/$name.log" 2>&1 &
  local pid=$!
  sleep 3
  local code
  code=$(curl -s -o /dev/null -w '%{http_code} %{time_total}s' --max-time 12 -x http://127.0.0.1:21999 https://www.gstatic.com/generate_204 2>/dev/null)
  printf '%-6s -> %s\n' "$name" "$code"
  kill $pid 2>/dev/null; wait $pid 2>/dev/null
  echo "   log: $(tail -2 "$D/$name.log" | tr '\n' ' ' | cut -c1-160)"
}

printf '\n----- LIVE TEST (same link, ech vs no ech) -----\n'
run_test noech
run_test ech

printf '\n----- DNS SANITY (ech resolver) -----\n'
getent hosts cloudflare-ech.com | head -2 || echo "  cannot resolve cloudflare-ech.com"
printf '  udp 1.1.1.1 reachable: '
timeout 4 bash -c 'echo >/dev/udp/1.1.1.1/53' 2>/dev/null && echo yes || echo unknown
