#!/usr/bin/env python3
import asyncio, hashlib, os, sys, time
sys.stdout.reconfigure(encoding='utf-8')
from pymobiledevice3.lockdown import create_using_usbmux
from pymobiledevice3.services.house_arrest import HouseArrestService

BID = 'com.huami.LoadController'
UDID = '00008130-001E084434DB803A'
LOCAL = r'E:\ios\GSMDriver-3.19.0-patched-unsigned.ipa'
NAME = 'GSMDriver-3.19.0-patched-unsigned.ipa'
VERIFY = r'E:\ios\work319\verify_lcsign_pull.ipa'


def sha256(p):
    h = hashlib.sha256()
    with open(p, 'rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
    return h.hexdigest()


async def main():
    local_size = os.path.getsize(LOCAL)
    local_sha = sha256(LOCAL)
    print('local size', local_size)
    print('local sha256', local_sha)

    ld = await create_using_usbmux(serial=UDID)
    async with await HouseArrestService.create(ld, BID, documents_only=False) as afc:
        # clean probes
        for p in ('/Documents/t_probe.txt', '/Documents/probe.txt', '/tmp/probe.txt', '/Library/Caches/probe.txt'):
            try:
                await afc.rm(p)
            except Exception:
                pass

        remote = '/Documents/' + NAME
        t0 = time.time()
        await afc.push(LOCAL, remote, progress_bar=False)
        print('push done in %.1fs' % (time.time() - t0))

        st = await afc.stat(remote)
        print('remote size', st.get('st_size'))
        dev_sha1 = (await afc.get_file_hash(remote)).hex()
        print('remote sha1', dev_sha1)

        if os.path.exists(VERIFY):
            os.remove(VERIFY)
        t0 = time.time()
        await afc.pull(remote, VERIFY)
        print('pull done in %.1fs' % (time.time() - t0))

    pull_size = os.path.getsize(VERIFY)
    pull_sha = sha256(VERIFY)
    print('pulled size', pull_size)
    print('pulled sha256', pull_sha)
    print('size match', pull_size == local_size)
    print('sha256 match', pull_sha == local_sha)


asyncio.run(main())
