#!/usr/bin/env python3
"""Build 59 - build 58 MINUS the build-info patch set.

Evidence chain:
  - build 56 (0 patches): no abort, shield runs, verdicts 1/11 -> ban page.
  - build 58 (45-era frameworks incl. build-info patches, pristine Driver): abort
    at Driver+0x328E0 (identical to 55/57).
  - The 45-era build-info patches are inherited BLIND from the 3.15 project
    (designed for a 7.8 MB build-info; applied to the 8.68 MB 3.19.0 one since
    build 19) - they corrupt the engine; on iOS 27 that kills the process in the
    real-app scene path.
  - The other patched frameworks (bshield/MDAPILayer/geolocator/MDOrderBusiness/
    MDMap/flutter_bshield_callback) differ from pristine ONLY at their known
    patch regions (no layout shifts) - safe to keep.

Build 59 = build 45's 6 patched frameworks + PRISTINE build-info + pristine
Driver + crypt fixes for the 4 stragglers.
"""
import os, sys, struct, zipfile, json

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'

# frameworks taken from build 45 (patched, same rip as PARTIAL)
FROM45 = ['Frameworks/bshield.framework/bshield',
          'Frameworks/MDAPILayer.framework/MDAPILayer',
          'Frameworks/geolocator_apple.framework/geolocator_apple',
          'Frameworks/MDOrderBusiness.framework/MDOrderBusiness',
          'Frameworks/MDMap.framework/MDMap',
          'Frameworks/flutter_bshield_callback.framework/flutter_bshield_callback']
# frameworks that still carry FairPlay-encrypted content in the PARTIAL
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)
    prefixes = {}
    for z in (z45, zp):
        for n in z.namelist():
            if n.endswith('Driver.app/Info.plist'):
                prefixes[z] = 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, n45, ncrypt = 0, 0, 0
    for n in sorted(zp.namelist()):
        if not n.startswith(prefixes[zp] + '/'):
            continue
        rel = n[len(prefixes[zp]) + 1:]
        if not rel or rel.endswith('/') or rel.startswith('PlugIns/'):
            continue
        try:
            head = zp.open(n).read(4)
        except Exception:
            continue
        if head != b'\xcf\xfa\xed\xfe':
            continue

        if rel == 'Driver':
            d = bytearray(zp.read(n))  # pristine decrypted (build 56's)
        elif rel in FROM45:
            d = bytearray(z45.read(prefixes[z45] + '/' + rel))
            n45 += 1
            print('from build 45: %s' % rel)
        else:
            d = bytearray(zp.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)
        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]
            ncrypt += 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 (from45: %d, crypt-fixed: %d)' % (done, n45, ncrypt))

    # expected checks: only the sites in the 6 kept frameworks that match build 45
    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned
    exp = []
    for rel, off, expbytes in make_unsigned.CHECKS:
        reln = rel.replace('\\', '/')
        if reln not in FROM45:
            continue
        data = z45.read(prefixes[z45] + '/' + reln)
        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)' % len(exp))


if __name__ == '__main__':
    main()
