#!/usr/bin/env python3
"""Build 62 - build 59 + the ban-decision predicate forced to ALWAYS CLEAN.

Chain traced (static, build-info 3.19.0):
  delegate method 0x28fecc (engine state, x19 = sp frame)
    -> 0x2908c4: bl 0x9608   (predicate on state object @x19+0x520)
    -> 0x2908c8: tbnz w0,#0, skip-ban   (w0 bit0 SET = clean, skip)
  0x9608 = `return 0xa1dc(state) == 0`  (0xa1dc = generic accessor, 396 callers -
           DO NOT TOUCH)
  0x9608 has 40 BL callers = every verdict consumer in the engine.

Patch: build-info 0x9608 -> `mov w0, #1; ret`  (the predicate always returns
"clean" for all 40 consumers = the detection always reports a valid code).
"""
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']

BI_SITE = (0x9608, 'f00310aaf10311aa', '20005280c0035fd6')


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)

    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))  # pristine
        elif rel in FROM45:
            d = bytearray(z45.read(prefixes[z45] + '/' + rel))
            n45 += 1
        elif rel == 'Frameworks/build-info.framework/build-info':
            d = bytearray(zp.read(n))
            off, orig, rep = BI_SITE
            nb = len(orig) // 2
            cur = bytes(d[off:off + nb]).hex()
            if cur != orig:
                sys.exit('BI SITE MISMATCH @0x%x: %s != %s' % (off, cur, orig))
            d[off:off + nb] = bytes.fromhex(rep)
            nbi += 1
            print('build-info: 0x%x %s -> %s (predicate always clean)' % (off, orig, rep))
        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 binaries (from45: %d, crypt-fixed: %d, bi-patches: %d)'
          % (done, n45, ncrypt, nbi))

    exp = [{'rel': 'Frameworks/build-info.framework/build-info',
            'off': BI_SITE[0], 'exp': BI_SITE[2]}]
    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned
    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()
