#!/usr/bin/env python3
"""Verify build 42 (window-creation probes) inside the zip, push, pull, compare."""
import asyncio, hashlib, os, sys, zipfile
sys.stdout.reconfigure(encoding='utf-8')
from pymobiledevice3.lockdown import create_using_usbmux
from pymobiledevice3.services.house_arrest import HouseArrestService

IPA = r'E:\ios\GSMDriver-3.19.0-patched42-unsigned.ipa'
NAME = 'GSMDriver-3.19.0-patched42-unsigned.ipa'
BID = 'com.huami.LoadController'
UDID = '00008130-001E084434DB803A'
PULL = r'E:\ios\work319\verify_patched42_pull.ipa'

z = zipfile.ZipFile(IPA)
d = z.read('Payload/Driver.app/Driver')
checks = {
    'Driver 0x32900 (PROBE W1 store)': (d[0x32900:0x32904].hex(), '2c0020d4'),
    'Driver 0x32918 (PROBE W2 reload)': (d[0x32918:0x3291c].hex(), '2d0020d4'),
    'Driver 0x329cc (PROBE W3 sub-tail)': (d[0x329cc:0x329d0].hex(), '2e0020d4'),
    'Driver 0x33398 (PROBE W4)': (d[0x33398:0x3339c].hex(), '2f0020d4'),
    'Driver 0x33344 (PROBE W5)': (d[0x33344:0x33348].hex(), '300020d4'),
    'Driver 0x33334 (PROBE W6)': (d[0x33334:0x33338].hex(), '310020d4'),
    'Driver 0x32bf8 (scene gate nop)': (d[0x32bf8:0x32bfc].hex(), '1f2003d5'),
    'Driver 0x32960 (storyboard RESTORED)': (d[0x32960:0x32964].hex(), '00a941f9'),
    'Driver 0x32a48 (window RESTORED)': (d[0x32a48:0x32a4c].hex(), '166d47f9'),
    'Driver 0x33374 (bail1 RESTORED)': (d[0x33374:0x33378].hex(), 'bf4301d1'),
    'Driver 0x3336c (bail2 RESTORED)': (d[0x3336c:0x33370].hex(), 'a08350f8'),
    'Driver 0x22c740 (banned gate)': (d[0x22c740:0x22c744].hex(), 'c0035fd6'),
}
ok = True
for k, (got, exp) in checks.items():
    print(k, got, 'OK' if got == exp else 'FAIL')
    ok = ok and got == exp
sig = [n for n in z.namelist() if '_CodeSignature' in n or 'SC_Info' in n or n.endswith('embedded.mobileprovision')]
print('signature artifacts:', len(sig))
print('zip verify:', 'OK' if ok and not sig else 'FAIL')

h = hashlib.sha256()
with open(IPA, 'rb') as f:
    for c in iter(lambda: f.read(1 << 20), b''):
        h.update(c)
local_sha = h.hexdigest()
print('size', os.path.getsize(IPA), 'sha256', local_sha)


async def main():
    ld = await create_using_usbmux(serial=UDID)
    async with await HouseArrestService.create(ld, BID, documents_only=False) as afc:
        remote = '/Documents/' + NAME
        await afc.push(IPA, remote, progress_bar=False)
        st = await afc.stat(remote)
        print('remote size', st.get('st_size'))
        if os.path.exists(PULL):
            os.remove(PULL)
        await afc.pull(remote, PULL)

asyncio.run(main())

h = hashlib.sha256()
with open(PULL, 'rb') as f:
    for c in iter(lambda: f.read(1 << 20), b''):
        h.update(c)
pull_sha = h.hexdigest()
print('pulled size', os.path.getsize(PULL), 'sha256', pull_sha)
print('MATCH' if pull_sha == local_sha else 'MISMATCH')
