#!/usr/bin/env python3
"""Final audit: quantify every byte build 55 changed vs the pristine binaries."""
import os, sys, struct, zipfile

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

PARTIAL_IPA = r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa'
APP = r'E:\ios\work319\patch_src\Payload\Driver.app'


def runs(diffs):
    out = []
    for i in diffs:
        if out and i == out[-1][1] + 1:
            out[-1][1] = i
        else:
            out.append([i, i])
    return out


def main():
    partial = zipfile.ZipFile(PARTIAL_IPA)
    pprefix = None
    for n in partial.namelist():
        if n.endswith('/Driver.app/Info.plist'):
            pprefix = n[:n.rfind('/')]
            break

    targets = ['Driver'] + [t[0].replace('\\', '/') for t in __import__('make_unsigned').CHECKS]
    targets = list(dict.fromkeys(targets))

    for rel in targets:
        try:
            base = partial.read(pprefix + '/' + rel)
        except KeyError:
            print('%s: not in PARTIAL' % rel)
            continue
        new = open(os.path.join(APP, rel.replace('/', os.sep)), 'rb').read()
        if len(base) != len(new):
            print('%s: SIZE CHANGED %d -> %d' % (rel, len(base), len(new)))
            continue
        diffs = [i for i in range(len(base)) if base[i] != new[i]]
        rr = runs(diffs)
        print('%-70s %d differing bytes in %d runs' % (rel, len(diffs), len(rr)))
        for a, b in rr[:40]:
            print('    0x%09x-0x%09x' % (a, b))
        if len(rr) > 40:
            print('    ... %d more runs' % (len(rr) - 40))


if __name__ == '__main__':
    main()
