#!/usr/bin/env python3
"""Verify build 40 (engine-stage 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-patched40-unsigned.ipa'
NAME = 'GSMDriver-3.19.0-patched40-unsigned.ipa'
BID = 'com.huami.LoadController'
UDID = '00008130-001E084434DB803A'
PULL = r'E:\ios\work319\verify_patched40_pull.ipa'

z = zipfile.ZipFile(IPA)
d = z.read('Payload/Driver.app/Driver')
b = z.read('Payload/Driver.app/Frameworks/build-info.framework/build-info')
checks = {
    'build-info 0x4d458 (PROBE N1)': (b[0x4d458:0x4d45c].hex(), '2c0020d4'),
    'build-info 0x240040 (PROBE N2)': (b[0x240040:0x240044].hex(), '2d0020d4'),
    'build-info 0x238084 (PROBE N3)': (b[0x238084:0x238088].hex(), '2e0020d4'),
    'build-info 0x25f2f0 (PROBE N4)': (b[0x25f2f0:0x25f2f4].hex(), '2f0020d4'),
    'build-info 0x29900 (PROBE N5)': (b[0x29900:0x29904].hex(), '300020d4'),
    'build-info 0x4ca80 (mod_init0 orig)': (b[0x4ca80:0x4ca84].hex(), 'f10311aa'),
    'build-info 0x4174 (get RESTORED)': (b[0x4174:0x417c].hex(), 'f00310aaf10311aa'),
    'build-info 0xe0d0 (verdict empty)': (b[0xe0d0:0xe0f0].hex(),
        'e03740f963481d94e03b00f91f2003d51f2003d51f2003d51f2003d501000014'),
    'build-info 0x760200 (addSubview)': (b[0x760200:0x760204].hex(), 'c0035fd6'),
    'build-info 0x760d20 (makeKeyAndVisible)': (b[0x760d20:0x760d24].hex(), 'c0035fd6'),
    'build-info 0x761460 (setRootVC)': (b[0x761460:0x761464].hex(), 'c0035fd6'),
    'Driver 0x3bc2c0 (PROBE H)': (d[0x3bc2c0:0x3bc2c4].hex(), '270020d4'),
    'Driver 0x246c58 (PROBE L)': (d[0x246c58:0x246c5c].hex(), '2a0020d4'),
    'Driver 0x3271c (PROBE K)': (d[0x3271c:0x32720].hex(), '290020d4'),
    'Driver 0x32bf8 (scene gate nop)': (d[0x32bf8:0x32bfc].hex(), '1f2003d5'),
    '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')
