#!/usr/bin/env python3
"""Build 48: rebuild the whole app bundle from the PROPER dump of 3.19.0.

For every module we dumped (the real 3.19.0 binaries), replace the corresponding
binary in patch_src, then re-apply every patch that make_unsigned.py checks,
clear cryptid, and verify everything.

This removes the TTJB 3.15 substitute frameworks, which is what was missing the
symbol that the real launch path needs."""
import os, sys, shutil, struct, json

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

PROPER = r'E:\ios\work319\proper319'
APP = r'E:\ios\work319\patch_src\Payload\Driver.app'
IPA_BACKUP = r'E:\ios\work319\patch_src_orig_payload'   # original on-disk files


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


def set_cryptid_zero(path):
    d = bytearray(open(path, 'rb').read())
    if struct.unpack_from('<I', d, 0)[0] != 0xFEEDFACF:
        return 'not-macho'
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    changed = 'already-0'
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:
            cur = struct.unpack_from('<I', d, off + 16)[0]
            if cur:
                struct.pack_into('<I', d, off + 16, 0)
                changed = '1->0'
            off = sz and off + sz
            break
        off += sz
    if changed == '1->0':
        open(path, 'wb').write(bytes(d))
    return changed


def main():
    checks = load_checks()
    by_base = {}
    for rel, off, exp in checks:
        by_base.setdefault(os.path.basename(rel), []).append((rel, off, exp))

    # map dumped module name -> app bundle relative path (via the bundle layout)
    fw_dir = os.path.join(APP, 'Frameworks')
    name_to_rel = {'Driver': 'Driver'}
    for d0 in sorted(os.listdir(fw_dir)):
        fwpath = os.path.join(fw_dir, d0)
        if not os.path.isdir(fwpath):
            continue
        for root, dirs, files in os.walk(fwpath):
            for fn in files:
                if fn == d0[:-len('.framework')] or fn.startswith(d0[:-len('.framework')] + '_'):
                    rel = os.path.relpath(os.path.join(root, fn), APP).replace('\\', '/')
                    name_to_rel.setdefault(d0[:-len('.framework')], rel)

    replaced, kept = [], []
    for mod in sorted(os.listdir(PROPER)):
        if mod.endswith(('.bin', '.json')):
            continue
        name = mod
        if not os.path.isfile(os.path.join(PROPER, mod)):
            continue
        rel = name_to_rel.get(name)
        if not rel:
            kept.append((name, 'no bundle counterpart'))
            continue
        dst = os.path.join(APP, rel.replace('/', os.sep))
        if not os.path.exists(dst):
            kept.append((name, 'target missing'))
            continue
        shutil.copyfile(os.path.join(PROPER, mod), dst)
        replaced.append((name, rel, os.path.getsize(dst)))

    print('replaced %d binaries from the proper dump:' % len(replaced))
    for n, r, sz in replaced:
        print('   %-34s %-52s %d' % (n, r, sz))
    print('kept as-is: %d' % len(kept))
    for n, why in kept:
        print('   %-34s %s' % (n, why))

    # apply every patch make_unsigned checks
    print('\napplying patches:')
    fails = []
    for rel, off, exp in checks:
        path = os.path.join(APP, rel.replace('/', os.sep))
        d = bytearray(open(path, 'rb').read())
        n = len(exp) // 2
        cur = bytes(d[off:off + n]).hex()
        if cur == exp:
            continue
        d[off:off + n] = bytes.fromhex(exp)
        open(path, 'wb').write(bytes(d))
        print('   %-52s 0x%06x -> %s' % (rel, off, exp[:24]))
    # verify
    for rel, off, exp in checks:
        path = os.path.join(APP, rel.replace('/', os.sep))
        d = open(path, 'rb').read()
        if d[off:off + len(exp) // 2].hex() != exp:
            fails.append((rel, off))
    print('patch verification: %d sites, %d failures' % (len(checks), len(fails)))
    for rel, off in fails:
        print('   FAIL %s 0x%x' % (rel, off))

    # cryptid
    print('\ncryptid:')
    done = set()
    for rel, off, exp in checks:
        p = os.path.join(APP, rel.replace('/', os.sep))
        if p in done:
            continue
        done.add(p)
        print('   %-52s %s' % (rel, set_cryptid_zero(p)))


if __name__ == '__main__':
    main()
