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

build() { # $1 file  $2 ip  $3 sni  $4 uuid  $5 fragment(true/false)
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":"$2","server_port":443,"uuid":"$4",
   "tls":{"enabled":true,"server_name":"$3","alpn":["http/1.1"],
          "utls":{"enabled":true,"fingerprint":"chrome"},
          "fragment":$5},
   "transport":{"type":"ws","path":"/","headers":{"Host":"$3"}}
 }],
 "route": {"final": "p"}
}
EOF
}

U1=e6df2095-a73c-4043-8693-8d5a03686870
U2=495c7195-85b8-498a-bf20-2ea9ce9175b5

build "$D/a_frag.json"    188.114.97.6  lucasjow.us.ci       "$U1" true
build "$D/a_nofrag.json"  188.114.97.6  lucasjow.us.ci       "$U1" false
build "$D/b_frag.json"    188.114.98.0  snip.edgeoneai.cc.cd "$U2" true
build "$D/c_frag.json"    104.21.91.244 lucasjow.us.ci       "$U1" true

probe() {
  local f=$1
  if ! $BIN check -c "$f" >"$f.check" 2>&1; then
    printf '  %-34s CHECK FAIL: %s\n' "$(basename $f)" "$(head -1 "$f.check" | cut -c1-90)"; 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 14 -x "http://127.0.0.1:$PORT" https://www.gstatic.com/generate_204 2>/dev/null)
  printf '  %-34s -> %s\n' "$(basename $f)" "${code:-fail}"
  if [ "${code%% *}" = "204" ]; then
    printf '  %-34s    exit-ip: %s\n' "" "$(curl -s --max-time 14 -x http://127.0.0.1:$PORT https://api.ipify.org 2>/dev/null)"
  fi
  kill $pid 2>/dev/null; wait $pid 2>/dev/null
  local lg; lg=$(grep -iE 'error|fatal' "$f.log" | tail -1 | cut -c1-110)
  [ -n "$lg" ] && printf '  %-34s    %s\n' "" "$lg"
}

echo "===== FRAGMENT vs NO-FRAGMENT ====="
probe "$D/a_nofrag.json"
probe "$D/a_frag.json"
probe "$D/b_frag.json"
probe "$D/c_frag.json"
