#!/usr/bin/env python3
"""Verify build 30 inside the zip, push to LCSign Documents, pull back, 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-patched34-unsigned.ipa'
NAME = 'GSMDriver-3.19.0-patched34-unsigned.ipa'
BID = 'com.huami.LoadController'
UDID = '00008130-001E084434DB803A'
PULL = r'E:\ios\work319\verify_patched34_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')
p = z.read('Payload/Driver.app/Frameworks/flutter_bshield_callback.framework/flutter_bshield_callback')
checks = {
    'build-info 0x4ca80 (mod_init0 RESTORED)': (b[0x4ca80:0x4ca84].hex(), 'f10311aa'),
    'build-info 0x75a4b0 (mod_init1 RESTORED)': (b[0x75a4b0:0x75a4b4].hex(), 'f44fbea9'),
    'build-info 0x5730 (addListener orig)': (b[0x5730:0x5734].hex(), 'f10311aa'),
    'build-info 0x4174 (get nil)': (b[0x4174:0x417c].hex(), '000080d2c0035fd6'),
    '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 0x3281c (abort1)': (d[0x3281c:0x32820].hex(), '1f2003d5'),
    'Driver 0x31fa8 (abort2)': (d[0x31fa8:0x31fac].hex(), '1f2003d5'),
    'Driver 0x333cc (tripwire1)': (d[0x333cc:0x333d0].hex(), '1f2003d5'),
    'Driver 0x35e4b4 (tripwire2)': (d[0x35e4b4:0x35e4b8].hex(), '1f2003d5'),
    'Driver 0x3b8e0c (tripwire3)': (d[0x3b8e0c:0x3b8e10].hex(), '1f2003d5'),
    'Driver 0x5de9c8 (tripwire4)': (d[0x5de9c8:0x5de9cc].hex(), '1f2003d5'),
    'Driver 0x22c740 (banned gate)': (d[0x22c740:0x22c744].hex(), 'c0035fd6'),
    'plugin 0x5020 (readAssets kill)': (p[0x5020:0x5024].hex(), '33000014'),
    'gadget dylib in zip': ('Payload/Driver.app/Frameworks/frida-gadget.dylib' in z.namelist(), True),
    'gadget config in zip': ('Payload/Driver.app/Frameworks/frida-gadget.config' in z.namelist(), True),
    'hook.js in zip': ('Payload/Driver.app/Frameworks/hook.js' in z.namelist(), True),
}
ok = True
for k, (got, exp) in checks.items():
    state = 'OK' if got == exp else 'FAIL'
    print(k, got, state)
    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')
