﻿#!/usr/bin/env python3
"""Build gsm50.tar straight from the ad-hoc IPA zip (no disk extraction -> no MAX_PATH issues).

Preserves unix modes and recreates symlinks, which a Windows unzip would destroy.
"""
import os, sys, tarfile, zipfile, time, stat

sys.stdout.reconfigure(encoding='utf-8')

IPA = r'E:\ios\GSMDriver-3.19.0-patched50-unsigned.ipa'
TAR = r'E:\ios\work319\gsm52.tar'

EXEC_SUFFIX = ('.dylib',)
EXEC_NAMES = {'Driver'}


def mode_for(name, zi):
    m = (zi.external_attr >> 16) & 0xFFFF
    if stat.S_ISLNK(m):
        return m
    if m & 0o777:
        return m
    base = os.path.basename(name)
    if base in EXEC_NAMES or base.endswith(EXEC_SUFFIX):
        return stat.S_IFREG | 0o755
    return stat.S_IFREG | 0o644


def main():
    t0 = time.time()
    with zipfile.ZipFile(IPA) as z, tarfile.open(TAR, 'w', format=tarfile.GNU_FORMAT) as tf:
        names = [n for n in z.namelist() if n.startswith('Payload/') and not n.endswith('/')]
        print('files in ipa payload:', len(names))
        dirs = set()
        for i, n in enumerate(names):
            zi = z.getinfo(n)
            rel = n[len('Payload/'):]           # Driver.app/...
            m = mode_for(n, zi)
            ti = tarfile.TarInfo(rel)
            ti.mtime = zi.date_time and time.mktime(zi.date_time + (0, 0, -1)) or 0
            ti.uid = ti.gid = 0
            ti.uname = 'root'
            ti.gname = 'wheel'
            ti.mode = m & 0o7777
            if stat.S_ISLNK(m):
                target = z.read(n).decode('utf-8', 'replace')
                ti.type = tarfile.SYMTYPE
                ti.linkname = target
                ti.size = 0
                tf.addfile(ti)
            else:
                ti.type = tarfile.REGTYPE
                ti.size = zi.file_size
                with z.open(n) as src:
                    tf.addfile(ti, src)
            # remember parent dirs so they exist with sane modes
            parent = os.path.dirname(rel)
            while parent and parent not in dirs:
                dirs.add(parent)
                parent = os.path.dirname(parent)
            if i % 5000 == 0:
                print('  ', i, '%.0fs' % (time.time() - t0), rel[:60])
        # add directory entries (tar creates parents implicitly, but be explicit)
        for d in sorted(dirs):
            ti = tarfile.TarInfo(d)
            ti.type = tarfile.DIRTYPE
            ti.mode = 0o755
            ti.uid = ti.gid = 0
            ti.uname = 'root'
            ti.gname = 'wheel'
            ti.mtime = int(t0)
            try:
                tf.addfile(ti)
            except Exception:
                pass
    print('tar: %.1f MB in %.1fs' % (os.path.getsize(TAR) / 1e6, time.time() - t0))


if __name__ == '__main__':
    main()






