#!/usr/bin/env python3
"""Build 60 - build 59 + ONLY the NOP at build-info+0x2910fc.

The single patch attributed by the build-44 test on the X: with this NOP the
ban screen went to ZERO rows (codes 1/5/11 disappeared). Everything else =
build 59 exactly (pristine build-info except this one NOP, pristine Driver,
build 45's 6 patched frameworks, 4 crypt fixes).
"""
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'

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']
DIRTY4 = ['Frameworks/FirebaseCoreExtension.framework/FirebaseCoreExtension',
          'Frameworks/MapboxCoreNavigationObjC.framework/MapboxCoreNavigationObjC',
          'Frameworks/MapboxDirectionsObjc.framework/MapboxDirectionsObjc',
          'Frameworks/MapboxNavigationObjC.framework/MapboxNavigationObjC']

VERDICT_CLUSTER = {0x2910fc}


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

    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned

    # the verdict-cluster sites: (offset, original, patched) on the PARTIAL build-info
    bi = zp.read(prefixes[zp] + '/Frameworks/build-info.framework/build-info')
    sites = []
    for rel, off, exp in make_unsigned.CHECKS:
        reln = rel.replace('\\', '/')
        if reln != 'Frameworks/build-info.framework/build-info' or off not in VERDICT_CLUSTER:
            continue
        nb = len(exp) // 2
        cur = bi[off:off + nb].hex()
        if cur == exp:
            print('  0x%x: no-op (already %s)' % (off, exp[:16]))
            continue
        sites.append((off, cur, exp))
        print('  0x%x: %s -> %s' % (off, cur[:32], exp[:32]))
    if not sites:
        print('!! no applicable verdict-cluster sites')

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

    done, n45, ncrypt, nbi = 0, 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))
        elif rel in FROM45:
            d = bytearray(z45.read(prefixes[z45] + '/' + rel))
            n45 += 1
        elif rel == 'Frameworks/build-info.framework/build-info':
            d = bytearray(bi)
            for off, cur, exp in sites:
                d[off:off + len(cur) // 2] = bytes.fromhex(exp)
                nbi += 1
            print('build-info: %d verdict-cluster patches applied' % nbi)
        else:
            d = bytearray(zp.read(n))

        co, cs, ci, coff = find_enc(bytes(d))
        if co is None:
            continue
        if ci != 0:
            struct.pack_into('<I', d, coff + 16, 0)
        if rel in DIRTY4 and cs > 0:
            mem = open(dumps[os.path.basename(rel)], 'rb').read()
            d[co:co + cs] = mem[co:co + cs]
            ncrypt += 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

    print('processed: %d (from45: %d, bi-patches: %d, crypt-fixed: %d)' % (done, n45, nbi, ncrypt))

    exp = []
    for off, cur, ex in sites:
        exp.append({'rel': 'Frameworks/build-info.framework/build-info', 'off': off, 'exp': ex})
    for rel, off, ex in make_unsigned.CHECKS:
        reln = rel.replace('\\', '/')
        if reln in FROM45:
            data = z45.read(prefixes[z45] + '/' + reln)
            if data[off:off + len(ex) // 2].hex() == ex:
                exp.append({'rel': reln, 'off': off, 'exp': ex})
    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()
