#!/bin/bash
export LC_ALL=C
BIN=/opt/proxy-lab/bin/sing-box
D=/tmp/sbech2; mkdir -p "$D"
PORT=21996
ECH='AEX+DQBBKwAgACAzTKV1en8B94rZLfdgNwYGVtFNgvroQwoUT1Uxljf8RQAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA='

mk() { # file host ip uuid [ech]
  local ech_field=""
  [ -n "${5:-}" ] && ech_field=",\"ech\":{\"enabled\":true,\"config\":\"$5\"}"
  cat > "$1" <<EOF
{
 "log": {"level": "warn"},
 "inbounds": [{"type":"mixed","tag":"in","listen":"127.0.0.1","listen_port":$PORT}],
 "outbounds": [{
   "type":"vless","tag":"p","server":"$3","server_port":443,"uuid":"$4",
   "tls":{"enabled":true,"server_name":"$2","alpn":["http/1.1"],
          "utls":{"enabled":true,"fingerprint":"chrome"}$ech_field},
   "transport":{"type":"ws","path":"/","headers":{"Host":"$2"}}
 }],
 "route":{"final":"p"}
}
EOF
}

mk "$D/lucas_ech.json"   lucasjow.us.ci       188.114.97.6  e6df2095-a73c-4043-8693-8d5a03686870 "$ECH"
mk "$D/lucas_noech.json" lucasjow.us.ci       188.114.97.6  e6df2095-a73c-4043-8693-8d5a03686870 ""
mk "$D/snip_ech.json"    snip.edgeoneai.cc.cd 188.114.98.0  495c7195-85b8-498a-bf20-2ea9ce9175b5 "$ECH"

probe() {
  local f=$1
  if ! $BIN check -c "$f" >"$f.check" 2>&1; then
    printf '  %-18s CHECK FAIL: %s\n' "$(basename "$f")" "$(head -1 "$f.check" | cut -c1-100)"; return
  fi
  $BIN run -c "$f" >"$f.log" 2>&1 &
  local pid=$!; sleep 3
  local code
  code=$(curl -s -o /dev/null -w '%{http_code} %{time_total}s' --max-time 15 -x "http://127.0.0.1:$PORT" https://www.gstatic.com/generate_204 2>/dev/null)
  printf '  %-18s -> %s\n' "$(basename "$f")" "${code:-fail}"
  if [ "${code%% *}" = "204" ]; then
    printf '  %-18s    exit-ip: %s\n' "" "$(curl -s --max-time 15 -x "http://127.0.0.1:$PORT" https://api.ipify.org 2>/dev/null)"
    printf '  %-18s    openai : %s\n' "" "$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -x "http://127.0.0.1:$PORT" https://api.openai.com/v1/models 2>/dev/null)"
  fi
  kill $pid 2>/dev/null; wait $pid 2>/dev/null
}

echo "===== THE DECIDING TEST ====="
probe "$D/lucas_noech.json"
probe "$D/lucas_ech.json"
probe "$D/snip_ech.json"
