#!/usr/bin/env python3
"""Verify build 21 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-patched21-unsigned.ipa'
NAME = 'GSMDriver-3.19.0-patched21-unsigned.ipa'
BID = 'com.huami.LoadController'
UDID = '00008130-001E084434DB803A'
PULL = r'E:\ios\work319\verify_patched21_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 = {
    'Driver 0x3271c': (d[0x3271c:0x32720].hex(), 'fc6fbaa9'),
    'Driver 0x31f8c': (d[0x31f8c:0x31f90].hex(), 'f85fbca9'),
    'Driver 0x3281c': (d[0x3281c:0x32820].hex(), '1f2003d5'),
    'Driver 0x31fa8': (d[0x31fa8:0x31fac].hex(), '1f2003d5'),
    'build-info 0x2c993c': (b[0x2c993c:0x2c9940].hex(), 'ff8300d1'),
    'build-info 0x2c5a44': (b[0x2c5a44:0x2c5a48].hex(), 'af631294'),
    'build-info 0x5730': (b[0x5730:0x5734].hex(), 'c0035fd6'),
    'build-info 0x4174': (b[0x4174:0x417c].hex(), '000080d2c0035fd6'),
}
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')
