#!/bin/bash
set -u
export LC_ALL=C
F=/opt/proxy-lab/proxylab.py

echo "===== 1) backup ====="
cp -a "$F" "$F.bak-ech-$(date +%Y%m%d-%H%M%S)" && ls -1 /opt/proxy-lab/proxylab.py.bak-ech-* | tail -2

echo
echo "===== 2) patch tls_block (add ECH) ====="
python3 - "$F" <<'PY'
import re
import sys

path = sys.argv[1]
src = open(path, encoding="utf-8").read()

if 'query_server_name' in src:
    print("  already patched - nothing to do")
    raise SystemExit(0)

anchor = '    if sec == "reality":'
if src.count(anchor) != 1:
    raise SystemExit(f"anchor found {src.count(anchor)} times - aborting")

addition = (
    '    ech = (p.get("ech") or "").strip()\n'
    '    if ech:\n'
    '        # "cloudflare-ech.com+udp://1.1.1.1" -> query that name for the ECHConfigList.\n'
    '        # Without this, SNI-filtered Cloudflare-edge configs fail their handshake.\n'
    '        qsn = re.split(r"[+\\s]", ech)[0].strip()\n'
    '        if qsn and re.match(r"^[A-Za-z0-9._-]+$", qsn):\n'
    '            t["ech"] = {"enabled": True, "query_server_name": qsn}\n'
)
src = src.replace(anchor, addition + anchor)
open(path, "w", encoding="utf-8").write(src)
print("  patched")
PY

echo
echo "===== 3) syntax check ====="
python3 -m py_compile "$F" && echo "  py_compile OK"

echo
echo "===== 4) parse a real blocked link through the patched parser ====="
python3 - <<'PY'
import importlib.util
spec = importlib.util.spec_from_file_location("proxylab", "/opt/proxy-lab/proxylab.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
link = ("vless://e6df2095-a73c-4043-8693-8d5a03686870@188.114.97.6:443"
        "?encryption=none&security=tls&sni=lucasjow.us.ci&fp=chrome&alpn=http%2F1.1"
        "&ech=cloudflare-ech.com%2Budp%3A%2F%2F1.1.1.1&type=ws&host=lucasjow.us.ci&path=%2F#test")
ob, name = m.parse_link(link)
import json
print("  outbound:", json.dumps(ob, indent=1)[:700])
PY
