#!/usr/bin/env python3
"""Push the restored framework binaries FLAT (one level, like drv53.bin which is
known to work), and generate the shell script that installs them."""
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:
        items = []
        for root, dirs, files in os.walk(OUT):
            for fn in files:
                p = os.path.join(root, fn)
                fwname = fn                       # e.g. syncfusion_flutter_pdfviewer
                flat = 'fwrest_%s.bin' % fwname
                rel = os.path.relpath(p, OUT).replace(os.sep, '/')
                items.append((p, flat, 'Frameworks/%s.framework/%s' % (fwname, fwname)))
        print('files to push:', len(items))
        n = 0
        for p, flat, devrel in items:
            try:
                await afc.set_file_contents('/' + flat, open(p, 'rb').read())
                n += 1
            except Exception as e:
                print('   err', flat, str(e)[:80])
        print('pushed', n)

        # install script
        lines = ["JB=$(ls -d /var/containers/Bundle/Application/.jbroot-* 2>/dev/null | head -1)",
                 "M=/rootfs/private/var/mobile/Media"]
        for p, flat, devrel in items:
            dst = '$JB/Applications/Driver.app/' + devrel
            lines.append('cp "$M/%s" "%s" && echo "restored %s"' % (flat, dst, devrel.split('/')[-1]))
            lines.append('"$JB/usr/bin/ldid" -S "%s" >/dev/null 2>&1 && echo "signed %s"' % (dst, devrel.split('/')[-1]))
        lines.append('echo FWRESTORE2_DONE')
        open(r'E:\ios\work319\fwrestore2.sh', 'w', encoding='utf-8').write('\n'.join(lines))
        print('wrote fwrestore2.sh (%d install pairs)' % len(items))


asyncio.run(main())
