# -*- coding: utf-8 -*-
"""Splice memory-decrypted crypt page into dumped binary, patch cryptid=0, re-zip IPA."""
import os, sys, struct, zipfile, shutil

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
PAYLOAD = os.path.join(OUT, "Payload")

def crypt_info(path):
    with open(path, 'rb') as f:
        d = f.read(1 << 20)
    ncmds = struct.unpack_from('<I', d, 16)[0]
    pos = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, pos)
        if cmd in (0x2C, 0x8000002C):
            return pos + 16, struct.unpack_from('<III', d, pos + 8)
        pos += sz
    return None, None

def find_app_dir():
    for n in os.listdir(PAYLOAD):
        if n.endswith('.app') and os.path.isdir(os.path.join(PAYLOAD, n)):
            return n
    return None

def main():
    app = sys.argv[1] if len(sys.argv) > 1 else find_app_dir()
    if not app:
        print("Khong thay .app trong Payload")
        return
    cryptbin = os.path.join(OUT, "mem_crypt.bin")
    if not os.path.exists(cryptbin):
        print("Khong co mem_crypt.bin")
        return
    page = open(cryptbin, 'rb').read()
    exe_path = os.path.join(PAYLOAD, app, "Driver")  # fallback
    # lay exe that tu Info.plist
    try:
        import plistlib
        with open(os.path.join(PAYLOAD, app, "Info.plist"), 'rb') as f:
            exe_name = plistlib.load(f).get('CFBundleExecutable', 'Driver')
    except Exception:
        exe_name = "Driver"
    exe_path = os.path.join(PAYLOAD, app, exe_name)
    off, info = crypt_info(exe_path)
    if not info:
        print("Khong co LC_ENCRYPTION_INFO trong", exe_name)
        return
    cryptoff, cryptsize, cryptid = info
    print("%s: cryptoff=%d cryptsize=%d cryptid=%d" % (exe_name, cryptoff, cryptsize, cryptid))
    if cryptsize != len(page):
        print("WARN: cryptsize (%d) != kich thuoc mem dump (%d) -> bo qua splice" % (cryptsize, len(page)))
        return
    with open(exe_path, 'r+b') as f:
        f.seek(cryptoff)
        f.write(page)
        f.seek(off)
        f.write(struct.pack('<I', 0))  # CHI 4 byte cryptid
    print("Da splice trang giai ma + patch cryptid=0")
    # kiem tra lai
    off2, info2 = crypt_info(exe_path)
    print("verify:", info2)

    short = app[:-4]
    ipa = os.path.join(OUT, short + ".ipa")
    with zipfile.ZipFile(ipa, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as z:
        app_root = os.path.join(PAYLOAD, app)
        for root, _dirs, fs in os.walk(app_root):
            for fn in fs:
                fp = os.path.join(root, fn)
                arc = os.path.join("Payload", app, os.path.relpath(fp, app_root)).replace('\\', '/')
                z.write(fp, arc)
    print("=== DONE: %s (%.1f MB) ===" % (ipa, os.path.getsize(ipa) / 1048576))

if __name__ == "__main__":
    main()
