#!/usr/bin/env python3
"""Extract the 3.15 reference pair (TTJB original vs bshieldPatched) and diff
every Mach-O to recover the REAL working 3.15 patch set (original+patched bytes)."""
import os, sys, zipfile, struct

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

ORIG = r'E:\ios\zsign-windows-x64\vn.gsm.md_6473405044_3.15.0_DecryptIPA_by_TTJB.zip'
PATCHED = r'E:\ios\zsign-windows-x64\GreenSMDriver-3.15.0_fake319_bshieldPatched.ipa'

zo = zipfile.ZipFile(ORIG)
zp = zipfile.ZipFile(PATCHED)


def app_prefix(names):
    for n in names:
        if n.endswith('Driver.app/Info.plist') or n.endswith('.app/Info.plist'):
            return n[:n.rfind('/')]
    return None


po = app_prefix(zo.namelist())
pp = app_prefix(zp.namelist())
print('orig prefix :', po)
print('patched pref:', pp)

mo = {}
for n in zo.namelist():
    if n.startswith(po + '/'):
        rel = n[len(po) + 1:]
        try:
            if zo.open(n).read(4) == b'\xcf\xfa\xed\xfe':
                mo[rel] = n
        except Exception:
            pass
mp = {}
for n in zp.namelist():
    if n.startswith(pp + '/'):
        rel = n[len(pp) + 1:]
        try:
            if zp.open(n).read(4) == b'\xcf\xfa\xed\xfe':
                mp[rel] = n
        except Exception:
            pass

print('orig binaries: %d   patched binaries: %d' % (len(mo), len(mp)))

diffs = {}
for rel in sorted(set(mo) & set(mp)):
    a = zo.read(mo[rel])
    b = zp.read(mp[rel])
    if len(a) != len(b):
        print('%-70s SIZE %d vs %d' % (rel, len(a), len(b)))
        continue
    d = [i for i in range(len(a)) if a[i] != b[i]]
    if not d:
        continue
    runs = []
    for i in d:
        if runs and i <= runs[-1][1] + 32:
            runs[-1][1] = i
        else:
            runs.append([i, i])
    diffs[rel] = (a, b, runs)
    print('%-70s %5d bytes diff in %3d runs' % (rel, len(d), len(runs)))

print()
print('total binaries with diffs:', len(diffs))
import json
out = {}
for rel, (a, b, runs) in diffs.items():
    out[rel] = []
    for s, e in runs:
        lo = max(0, s - 64)
        hi = min(len(a), e + 1 + 64)
        out[rel].append({
            'start': s, 'end': e,
            'orig': a[s:e + 1].hex(),
            'patched': b[s:e + 1].hex(),
            'ctx_orig_before': a[lo:s].hex(),
            'ctx_orig_after': a[e + 1:hi].hex(),
        })
json.dump(out, open(r'E:\ios\work319\patch315_real.json', 'w'), indent=1)
print('written patch315_real.json')
