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

BID = 'com.huami.LoadController'
UDID = '00008130-001E084434DB803A'
PROBE = r'E:\ios\work319\t_probe.txt'


async def main():
    ld = await create_using_usbmux(serial=UDID)
    for docs in (True, False):
        tag = 'DOCS' if docs else 'CONTAINER'
        try:
            async with await HouseArrestService.create(ld, BID, documents_only=docs) as afc:
                print(tag, 'root listing:', await afc.listdir('/'))
                for p in ('/', '/Documents', '/tmp'):
                    try:
                        st = await afc.stat(p)
                        print(tag, 'stat', p, {k: v for k, v in st.items() if k in ('st_size', 'st_ifmt')})
                    except Exception as e:
                        print(tag, 'stat', p, 'ERR', type(e).__name__, e)
                try:
                    await afc.set_file_contents('/probe_lcsign.txt', b'probe')
                    print(tag, 'write /probe_lcsign.txt OK')
                except Exception as e:
                    print(tag, 'write /probe_lcsign.txt ERR', type(e).__name__, e)
        except Exception as e:
            print(tag, 'OPEN ERR', type(e).__name__, e)

    try:
        async with AfcService(ld) as media:
            await media.push(PROBE, '/t_probe_media.txt')
            h = await media.get_file_hash('/t_probe_media.txt')
            local = hashlib.sha256(open(PROBE, 'rb').read()).digest()
            print('media hash bytes:', h.hex(), 'len', len(h))
            print('matches local sha256:', h == local)
    except Exception as e:
        print('MEDIA ERR', type(e).__name__, e)


asyncio.run(main())
