#!/usr/bin/env python3
import json
import sys
from pathlib import Path

ROOT = Path("/opt/ws-remote")
SID = "056e573923205845"
BASE = "https://209.50.60.133.sslip.io"
KEY = Path("/tmp/opencode/timing_key.txt").read_text().strip()
template = (ROOT / "luraph_pack/loader_guard.luau").read_text()
template = template.replace("-- __SOCKET_SIGN__\n",
                            (ROOT / "luraph_pack/socket_sign.luau").read_text())
ws = BASE.replace("https://", "wss://", 1) + "/ws?role=secroauth&script_id=" + SID + "&bin=1"
clear = (template.replace("__SID__", json.dumps(SID))
         .replace("__WS__", json.dumps(ws)))
clear = "script_key = " + json.dumps(KEY) + "\n" + clear
clear = clear.replace(
    'local text = "v3|auth_ok|" .. SCRIPT_ID .. "|" .. nonce .. "|"',
    'local text = "v3|auth_ok|" .. SCRIPT_ID .. "|" .. nonce .. "|"')
# Add prints after the auth_ok text assignment (the `tostring(expected_check)` line).
needle = '.. tostring(expected_check)\n                if __hmachex(k_auth, text) ~= tostring(data.sig or "") then'
repl = ('.. tostring(expected_check)\n'
        '                print("[dbg] text", text)\n'
        '                print("[dbg] keyhash", __sha256hex(script_key))\n'
        '                print("[dbg] salt", auth_salt)\n'
        '                print("[dbg] kauth", tohex(k_auth))\n'
        '                print("[dbg] kauth2", tohex(__hkdf(script_key, auth_salt, "secro-auth-v3")))\n'
        '                print("[dbg] sig_got", tostring(data.sig or ""))\n'
        '                print("[dbg] sig_want", __hmachex(k_auth, text))\n'
        '                if __hmachex(k_auth, text) ~= tostring(data.sig or "") then')
if needle not in clear:
    raise SystemExit("needle not found")
clear = clear.replace(needle, repl, 1)
sys.path.insert(0, str(ROOT))
import secro_mode
protected = secro_mode.build(clear)
Path("/tmp/opencode/loader_debug_psk.lua").write_text(protected)
print("bytes", len(protected.encode()))
