#!/usr/bin/env python3
"""Push the restored framework binaries to the device (AFC), creating dirs."""
import asyncio, os, sys

sys.stdout.reconfigure(encoding='utf-8')
from pymobiledevice3.lockdown import create_using_usbmux
from pymobiledevice3.services.afc import AfcService

UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'
OUT = r'E:\ios\work319\fw_restore'


async def main():
    ld = await create_using_usbmux(serial=UDID)
    async with AfcService(ld) as afc:
        # collect files
        items = []
        for root, dirs, files in os.walk(OUT):
            for fn in files:
                p = os.path.join(root, fn)
                rel = os.path.relpath(p, OUT).replace(os.sep, '/')
                items.append((p, '/fw_restore/' + rel))
        print('files to push:', len(items))

        # create directories first
        dirs = set()
        for p, remote in items:
            d = os.path.dirname(remote)
            while d and d != '/':
                dirs.add(d)
                d = os.path.dirname(d)
        for d0 in sorted(dirs):
            try:
                await afc.mkdir(d0)
            except Exception:
                pass
        print('dirs ensured:', len(dirs))

        n = 0
        for p, remote in items:
            try:
                await afc.set_file_contents(remote, open(p, 'rb').read())
                n += 1
            except Exception as e:
                print('   err', remote, str(e)[:80])
        print('pushed', n)
        l = await afc.listdir('/fw_restore')
        print('verify /fw_restore entries:', len(l))


asyncio.run(main())
