#!/usr/bin/env python3
"""Build 58 - THE CORRECTED COMPOSITION.

Root cause of build 57's crash finally established:
  - The 45-era pipeline used a build-info file that is a SLIGHTLY DIFFERENT
    COMPILATION from the current PARTIAL IPA's build-info (7 pages, instruction
    shifts like +16 bytes at 0xe0d0). The CHECKS build-info offsets are valid
    ONLY for the 45-era file.
  - Builds 55-57 rewrote patch_src binaries from the CURRENT PARTIAL, so build
    57 applied the build-info patches at WRONG offsets = 18 corruption writes
    -> abort in the real-app scene path.

Build 58 composition:
  1. EVERYTHING from the build 45 IPA (the 45-era, correctly-patched set -
     proven: verdicts fully suppressed, 'zero rows' on the X).
  2. Driver = build 56's pristine decrypted Driver (no 6 neuters - proven to
     run the real app path on iOS 27).
  3. The 4 FairPlay-straggler frameworks (FirebaseCoreExtension,
     MapboxCoreNavigationObjC, MapboxDirectionsObjc, MapboxNavigationObjC)
     crypt-swapped from the memory dumps (iOS 27 requires decrypted content).
  4. cryptid=0 verified everywhere.
"""
import os, sys, struct, zipfile

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

IPA45 = r'E:\ios\GSMDriver-3.19.0-patched45-unsigned.ipa'
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'

DIRTY4 = ['Frameworks/FirebaseCoreExtension.framework/FirebaseCoreExtension',
          'Frameworks/MapboxCoreNavigationObjC.framework/MapboxCoreNavigationObjC',
          'Frameworks/MapboxDirectionsObjc.framework/MapboxDirectionsObjc',
          'Frameworks/MapboxNavigationObjC.framework/MapboxNavigationObjC']


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():
    z45 = zipfile.ZipFile(IPA45)
    zp = zipfile.ZipFile(PARTIAL_IPA)
    prefix45 = None
    for n in z45.namelist():
        if n.endswith('Driver.app/Info.plist'):
            prefix45 = n[:n.rfind('/')]
            break

    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))

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

        if rel == 'Driver':
            # pristine decrypted Driver from the current PARTIAL (== build 56's)
            d = bytearray(zp.read(prefix45 + '/Driver'))
            drivers_swapped += 1
            print('Driver: replaced with build-56 pristine decrypted binary')
        else:
            d = bytearray(z45.read(n))

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

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

        # crypt-swap ONLY the 4 known-encrypted stragglers
        if rel in DIRTY4 and cs > 0:
            dp = dumps.get(os.path.basename(rel))
            if not dp:
                sys.exit('no dump for %s' % rel)
            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]
            crypt_fixed += 1
            print('crypt-decrypted: %s' % rel)

        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 (Driver swapped: %d, crypt-fixed: %d)' % (done, drivers_swapped, crypt_fixed))

    # write expected checks = verify the 45-era patched sites are present
    import json
    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned
    exp = []
    z45b = zipfile.ZipFile(IPA45)
    for rel, off, expbytes in make_unsigned.CHECKS:
        reln = rel.replace('\\', '/')
        if reln == 'Driver':
            continue  # Driver is pristine now - all its CHECKS are no-ops or excluded
        try:
            data = z45b.read(prefix45 + '/' + reln)
        except KeyError:
            continue
        got = data[off:off + len(expbytes) // 2].hex()
        if got == expbytes:
            exp.append({'rel': reln, 'off': off, 'exp': expbytes})
    json.dump(exp, open(r'E:\ios\work319\expected_checks.json', 'w'), indent=1)
    print('expected_checks.json written (%d sites verified against build 45)' % len(exp))


if __name__ == '__main__':
    main()
