# Copyright (C) 2026 CoelhoFZ
# SPDX-License-Identifier: GPL-3.0-only
# This file is part of unlocker-CoelhoFZ (GPLv3, see LICENSE).

"""gen_xor.py - generates common/enc_strings.h with XOR-encrypted strings.

The plaintext only exists HERE (source) and in the build script; the final
binary only contains the encrypted bytes + the key. dec() decrypts at runtime.

Usage: python3 tools/gen_xor.py > common/enc_strings.h  (do not edit by hand)
"""

KEY = 0x5A
STRINGS = [
    ("kIniName",       "unlock-CoelhoFZ.ini"),     # dev-only (harden: embedded config)
    ("kShimName",      "XGameCore.GDK.dll"),        # innocuous name (blends into the Content GDK)
    ("kProdIdDef",     "9NBLGGH2JHXJ"),
    ("kItemUrl",       "https://coelhofz.example/logo.png"),
    ("kItemBrand",     "CoelhoFZ"),
    ("kItemMagic",     "1337"),
    ("kItemOffer",     "0010"),
    ("kQueryApiImpl",  "QueryApiImpl"),
    ("kXgameruntime",  "xgameruntime.dll"),
    ("kNtdll",         "ntdll.dll"),
    ("kNtQuery",       "NtQueryInformationProcess"),
    # Target process gate (common/target_process.h): Minecraft Bedrock
    # identity. Lowercase - the comparison in the header is case-insensitive.
    ("kPkgPrefix",     "microsoft.minecraft"),     # package family (UWP/Preview/Education)
    ("kGameExe",       "minecraft.windows.exe"),   # game exe basename
]

def xor(s, k):
    return bytes(ord(c) ^ ((k + i) & 0xFF) for i, c in enumerate(s))

# Copyright notice emitted by the generator, identical to the header the
# published file carries (full text of the license in ../LICENSE).
COPYRIGHT = [
    "// Copyright (C) 2026 CoelhoFZ",
    "// SPDX-License-Identifier: GPL-3.0-only",
    "// This file is part of unlocker-CoelhoFZ (GPLv3, see LICENSE).",
    "",
]

out = []
out += COPYRIGHT
out.append("// enc_strings.h - GENERATED by tools/gen_xor.py. DO NOT edit by hand.")
out.append("// XOR-encrypted strings: the plaintext does not exist in the binary.")
out.append("#pragma once")
out.append("#include <cstddef>")
out.append("#include <cstdint>")
out.append("namespace enc {")
out.append("inline const char* dec(const uint8_t* in, size_t n, uint8_t k) {")
out.append("    static char buf[128];")
out.append("    // volatile prevents constant-folding (runtime decryption)")
out.append("    volatile uint8_t vk = k;")
out.append("    for (size_t i = 0; i < n && i < 127; ++i)")
out.append("        buf[i] = static_cast<char>(in[i] ^ static_cast<uint8_t>(vk + i));")
out.append("    buf[n] = '\\0';")
out.append("    return buf;")
out.append("}")
out.append("")
for name, s in STRINGS:
    b = xor(s, KEY)
    hexs = ", ".join("0x%02X" % x for x in b)
    out.append(f"constexpr uint8_t {name}[{len(b)}] = {{{hexs}}};")
    out.append(f"constexpr size_t {name}Len = {len(b)};")
    out.append("")
out.append("}  // namespace enc")
out.append("")
print("\n".join(out))
print("// key used: 0x%02X" % KEY, file=__import__("sys").stderr)
