#!/usr/bin/env python3
"""Stage build 41 (ad-hoc signed) as a single tar for on-device install via root shell."""
import os, sys, tarfile, zipfile, shutil, time

sys.stdout.reconfigure(encoding='utf-8')

IPA = r'E:\ios\work319\GSMDriver-3.19.0-patched41-adhoc.ipa'
STAGE = r'E:\ios\work319\stage41'
TAR = r'E:\ios\work319\gsm41.tar'

if os.path.isdir(STAGE):
    shutil.rmtree(STAGE)
os.makedirs(STAGE)

t0 = time.time()
with zipfile.ZipFile(IPA) as z:
    names = [n for n in z.namelist() if n.startswith('Payload/')]
    print('ipa entries:', len(names))
    for i, n in enumerate(names):
        if n.endswith('/'):
            continue
        dst = os.path.join(STAGE, n.replace('/', os.sep))
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        with z.open(n) as src, open(dst, 'wb') as out:
            shutil.copyfileobj(src, out, 1024 * 1024)
        if i % 5000 == 0:
            print('  extracted', i, '%.0fs' % (time.time() - t0))
print('extract done %.1fs' % (time.time() - t0))

app = os.path.join(STAGE, 'Payload', 'Driver.app')
print('app dir exists:', os.path.isdir(app))
for f in ('Driver', 'Info.plist', 'embedded.mobileprovision'):
    p = os.path.join(app, f)
    print(' ', f, os.path.getsize(p) if os.path.exists(p) else 'MISSING')

with tarfile.open(TAR, 'w') as tf:
    tf.add(app, arcname='Driver.app')
print('tar written %.1f MB in %.1fs' % (os.path.getsize(TAR) / 1e6, time.time() - t0))
