#!/usr/bin/env python3
"""Build 54 - THE CONSERVATIVE APPROACH.

Every binary = the ORIGINAL App Store binary (from the PARTIAL IPA / ipatool IPA)
with ONLY these changes:
  1. __TEXT segment overwritten with the decrypted pages from the memory dump
  2. cryptid 1 -> 0
  3. Driver only: the 6 detector neuters

__DATA, __DATA_CONST, __LINKEDIT, load commands = 100% original from Apple.
dyld binds everything from the original bind stream, exactly as the App Store app
does. No mixing, no memory-image __DATA, no runtime pointers baked in.
"""
import os, sys, struct, zipfile, shutil

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

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

DRIVER_NEUTERS = [
    (0x22C740, 4, 'c0035fd6'),
    (0x1709780, 8, '00008052c0035fd6'),
    (0x170867C, 4, 'e0031faa'),
    (0x1708684, 4, 'e1031faa'),
    (0x17086BC, 4, 'e0031faa'),
    (0x17086C0, 4, 'e1031faa'),
]


def load_commands(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    segs = []
    crypt = None
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            nm = d[off+8:off+24].rstrip(b'\0').decode()
            vm, vs, fo, fs = struct.unpack_from('<QQQQ', d, off+24)
            segs.append((nm, vm, vs, fo, fs))
        elif cmd == 0x2C:
            crypt = struct.unpack_from('<4I', d, off+8)
        off += sz
    return segs, crypt


def main():
    # 1. load the PARTIAL IPA (has all the original binaries)
    partial = zipfile.ZipFile(PARTIAL_IPA)
    # 2. load the ipatool IPA (pristine App Store, for the Driver)
    apptool = zipfile.ZipFile(APPTOOL_IPA)

    # 3. load the memory dumps
    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))

    # 4. enumerate all binaries in the app bundle
    # find the app dir in the PARTIAL IPA
    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)

    binaries = []
    for n in sorted(partial.namelist()):
        if not n.startswith(app_prefix + '/'):
            continue
        rel = n[len(app_prefix)+1:]
        if rel.endswith('/') or not rel:
            continue
        try:
            head = partial.open(n).read(4)
        except Exception:
            continue
        if head == b'\xcf\xfa\xed\xfe':
            binaries.append(rel)
    print('binaries in app bundle: %d' % len(binaries))

    # 5. process each binary
    done, skipped = 0, 0
    for rel in binaries:
        iname = app_prefix + '/' + rel
        dst = os.path.join(APP, rel.replace('/', os.sep))

        # base: the ORIGINAL App Store binary
        # (from ipatool for Driver, from PARTIAL IPA for frameworks)
        if rel == 'Driver':
            base = apptool.read([n for n in apptool.namelist() if n.endswith('Driver.app/Driver')][0])
        else:
            try:
                base = partial.read(iname)
            except KeyError:
                skipped += 1
                continue

        d = bytearray(base)
        segs, crypt = load_commands(bytes(d))
        text_seg = next(s for s in segs if s[0] == '__TEXT')
        text_vm, text_fo, text_fs = text_seg[1], text_seg[3], text_seg[4]

        # 5a. overwrite __TEXT with the decrypted memory content
        dump_path = dumps.get(rel)
        if dump_path and os.path.exists(dump_path):
            mem = open(dump_path, 'rb').read()
            src_off = text_vm - text_vm  # = 0 for the first segment
            # the memory dump starts at base (== slide + text_vm)
            # so memory[text_vm_offset] = the decrypted __TEXT
            avail = min(text_fs, len(mem))
            if avail >= text_fs:
                d[text_fo:text_fo + text_fs] = mem[0:text_fs]
            else:
                d[text_fo:text_fo + avail] = mem[0:avail]
        # else: no dump available, keep the encrypted __TEXT (will fail)

        # 5b. cryptid -> 0
        ncmds, = struct.unpack_from('<I', d, 16)
        off = 32
        for _ in range(ncmds):
            cmd, sz = struct.unpack_from('<II', d, off)
            if cmd == 0x2C:
                struct.pack_into('<I', d, off + 16, 0)
                break
            off += sz

        # 5c. apply ALL patches from make_unsigned.py's CHECKS list
        sys.path.insert(0, r'E:\ios\work319')
        import make_unsigned
        rel_norm = rel.replace('/', '\\')
        for crel, coff, cexp in make_unsigned.CHECKS:
            if crel.replace('/', '\\') != rel_norm:
                continue
            nbytes = len(cexp) // 2
            d[coff:coff + nbytes] = bytes.fromhex(cexp)

        os.makedirs(os.path.dirname(dst), exist_ok=True)
        open(dst, 'wb').write(bytes(d))
        done += 1

    print('processed: %d binaries (decrypted __TEXT + cryptid=0 + neuters for Driver)' % done)
    print('skipped: %d (not in PARTIAL IPA)' % skipped)


if __name__ == '__main__':
    main()
