#!/usr/bin/env python3
"""Build 56 - PRISTINE DECRYPTED BASELINE.

Exactly build 55 minus EVERY patch. Each binary = pristine App Store binary,
FairPlay region decrypted from the memory dump, cryptid=0. Nothing else.

Purpose: prove the decrypt/resign pipeline works on iOS 27 with zero code
modification. Any crash from here is either the shield doing its real checks
or a pipeline issue - no longer our patch corruption.
"""
import os, sys, struct, zipfile

sys.stdout.reconfigure(encoding='utf-8')

PARTIAL_IPA = r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa'
DUMPDIR = r'E:\ios\work319\dump319'
APP = r'E:\ios\work319\patch_src\Payload\Driver.app'


def find_enc(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:
            co, cs, ci = struct.unpack_from('<3I', d, off + 8)
            return co, cs, ci, off
        off += sz
    return None, None, None, None


def main():
    partial = zipfile.ZipFile(PARTIAL_IPA)

    dumps = {}
    for fn in os.listdir(DUMPDIR):
        if fn.endswith('.bin'):
            dumps[fn[:-4]] = os.path.join(DUMPDIR, fn)
    print('memory dumps: %d' % len(dumps))

    app_prefix = None
    for n in partial.namelist():
        if n.endswith('/Driver.app/Info.plist'):
            app_prefix = n[:n.rfind('/')]
            break

    done, swapped = 0, 0
    for n in sorted(partial.namelist()):
        if not n.startswith(app_prefix + '/'):
            continue
        rel = n[len(app_prefix) + 1:]
        if not rel or rel.endswith('/') or rel.startswith('PlugIns/'):
            continue
        try:
            head = partial.open(n).read(4)
        except Exception:
            continue
        if head != b'\xcf\xfa\xed\xfe':
            continue

        d = bytearray(partial.read(n))
        co, cs, ci, coff = find_enc(bytes(d))
        if co is None:
            print('!! no LC_ENCRYPTION_INFO: %s' % rel)
            continue

        if cs > 0 and ci != 0:
            dp = dumps.get(os.path.basename(rel))
            if dp:
                mem = open(dp, 'rb').read()
                if len(mem) < co + cs:
                    sys.exit('dump too small for %s' % rel)
                d[co:co + cs] = mem[co:co + cs]
                swapped += 1
            else:
                print('  (no dump, leaving encrypted content) %s' % rel)

        if ci != 0:
            struct.pack_into('<I', d, coff + 16, 0)

        dst = os.path.join(APP, rel.replace('/', os.sep))
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        open(dst, 'wb').write(bytes(d))
        done += 1

    print('processed: %d binaries (%d crypt-swapped) - ZERO patches applied' % (done, swapped))


if __name__ == '__main__':
    main()
