#!/usr/bin/env python3
import hashlib
import hmac
import json
import secrets
import subprocess
import sys
import tempfile
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()
secret = json.loads((ROOT / "secroauth.json").read_text())["secret"]
signkey = hmac.new(secret.encode(), ("socket-v2:" + SID).encode(), hashlib.sha256).hexdigest()
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))
         .replace("__SIGN__", json.dumps(signkey)))
clear = "script_key = " + json.dumps(KEY) + "\n" + clear
Path("/tmp/opencode/loader_clear.luau").write_text(clear)

sys.path.insert(0, str(ROOT / "luraph_pack"))
import packer
import secro_wrapper

key = secrets.randbelow(256)
with tempfile.TemporaryDirectory() as td:
    src = Path(td) / "loader.luau"
    inner = Path(td) / "inner.luau"
    src.write_text(clear)
    proc = subprocess.run([
        sys.executable, str(ROOT / "luraph_compiler/compiler.py"),
        str(src), "-o", str(inner), "--key", str(key), "--hardened",
    ], capture_output=True, timeout=120)
    print("compiler", proc.returncode, (proc.stderr or b"")[-300:])
    carrier = packer.pack(inner.read_text(), seed=key)
    mono = secro_wrapper.wrap(carrier, seed=key)
    Path("/tmp/opencode/loader_secro_mono.lua").write_text(mono)
    print("mono bytes", len(mono.encode()), "inner", inner.stat().st_size)
