#!/usr/bin/env python3
"""Build 57 - build 56 (pristine decrypted) + the verdict-suppression patch set.

Known facts driving this build:
- Build 56 on the 15 Pro: the REAL app launches (UI runs) and the shield's
  repack detection fires verdicts 1 + 11 -> blocking web page.
- Build 45 on the X (same 3.19.0 binaries + the 65-site set): ban screen with
  ZERO rows -> the set suppresses every verdict. The Driver was corrupted by
  only 6 'neuters' (function prologues / argument setup) which silently broke
  the real-app path - that corruption is what we removed in build 56.
- Therefore: apply the proven suppression set EXCLUDING the 6 harmful Driver
  neuters. All remaining Driver sites are byte-level no-ops (verified), so the
  Driver stays 100% pristine.
"""
import os, sys, struct, zipfile, json

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

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'

# the 6 proven-harmful Driver neuter sites (3.15 layout, wrong for 3.19.0)
EXCLUDE = {
    ('Driver', 0x22C740),
    ('Driver', 0x1709780),
    ('Driver', 0x170867C),
    ('Driver', 0x1708684),
    ('Driver', 0x17086BC),
    ('Driver', 0x17086C0),
}


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():
    sys.path.insert(0, r'E:\ios\work319')
    import make_unsigned

    CHECKS = []
    for rel, off, exp in make_unsigned.CHECKS:
        if (rel, off) in EXCLUDE:
            print('excluded harmful neuter: %s @0x%x' % (rel, off))
            continue
        CHECKS.append((rel, off, exp))
    print('patch sites to apply: %d (of %d)' % (len(CHECKS), len(make_unsigned.CHECKS)))

    partial = zipfile.ZipFile(PARTIAL_IPA)

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

    app_prefix = None
    for n in partial.namelist():
        if n.endswith('/Driver.app/Info.plist'):
            app_prefix = n[:n.rfind('/')]
            break

    by_rel = {}
    for rel, off, exp in CHECKS:
        by_rel.setdefault(rel, []).append((off, exp))

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

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

        if cs > 0 and ci != 0:
            dp = dumps.get(os.path.basename(rel))
            if dp:
                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]
                swapped += 1

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

        rel_norm = rel.replace('/', '\\')
        for off, exp in by_rel.get(rel_norm, []):
            nb = len(exp) // 2
            cur = bytes(d[off:off + nb]).hex()
            d[off:off + nb] = bytes.fromhex(exp)
            if cur == exp:
                noop_n += 1
            else:
                patched_n += 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 (%d crypt-swapped)' % (done, swapped))
    print('patches: %d real writes, %d no-ops' % (patched_n, noop_n))

    exp_json = [{'rel': rel.replace('\\', '/'), 'off': off, 'exp': exp} for rel, off, exp in CHECKS]
    json.dump(exp_json, open(r'E:\ios\work319\expected_checks.json', 'w'), indent=1)
    print('expected_checks.json written (%d sites)' % len(exp_json))


if __name__ == '__main__':
    main()
