#!/usr/bin/env python3
"""Build 55 - THE MINIMAL CORRECT APPROACH.

Every binary = the pristine App Store binary (PARTIAL IPA, proven byte-identical
to the ipatool original outside the crypt region) with ONLY:

  1. the FairPlay crypt region [cryptoff, cryptoff+cryptsize) replaced with the
     decrypted bytes from the memory dump (no-op for the 166 already-decrypted
     binaries + Driver; actually decrypts the 4 stragglers:
     FirebaseCoreExtension, MapboxCoreNavigationObjC, MapboxDirectionsObjc,
     MapboxNavigationObjC)
  2. cryptid -> 0
  3. the 65 CHECKS patches (make_unsigned.CHECKS, includes the 6 neuters)

__DATA, __DATA_CONST, __LINKEDIT, load commands = 100% from the original file.
No memory-image pointers, no runtime-optimized ObjC metadata.
"""
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():
    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned

    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
    print('app prefix:', app_prefix)

    done, noswap = 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

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

        swapped = False
        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: 0x%x < 0x%x' % (rel, len(mem), co + cs))
                d[co:co + cs] = mem[co:co + cs]
                swapped = True

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

        # CHECKS patches (includes the 6 detector neuters for Driver)
        rel_norm = rel.replace('/', '\\')
        npatch = 0
        for crel, coff2, cexp in make_unsigned.CHECKS:
            if crel.replace('/', '\\') != rel_norm:
                continue
            nb = len(cexp) // 2
            d[coff2:coff2 + nb] = bytes.fromhex(cexp)
            npatch += 1

        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
        if swapped:
            print('decrypted crypt region: %s (%d patches)' % (rel, npatch))
        else:
            noswap += 1

    print('processed: %d binaries (%d crypt-swapped, %d already-clean)' % (done, done - noswap, noswap))


if __name__ == '__main__':
    main()
