#!/usr/bin/env python3
"""
make_unsigned.py - build an unsigned, patched GSM Driver 3.19.0 IPA.

Source : E:\ios\work319\patch_src  (bundle id vn.gsm.md, patches already applied)
Output : E:\ios\GSMDriver-3.19.0-patched-unsigned.ipa

Strips every signature artifact (_CodeSignature, SC_Info, embedded.mobileprovision)
and the attachment-only NotificationServiceExtension, so the IPA can be re-signed
per device with Sideloadly / AltStore / ESign / zsign / an enterprise profile.
"""
import os, sys, time, zipfile, hashlib, plistlib, struct

SRC = r'E:\ios\work319\patch_src'
APP = os.path.join(SRC, 'Payload', 'Driver.app')
OUT = r'E:\ios\GSMDriver-3.19.0-patched62-unsigned.ipa'

# NotificationServiceExtension is attachment-only (no setTitle/setBody/setSound);
# standard alerts do not need it, and its app-id suffix is not authorized by
# fixed profiles. Drop it so the IPA re-signs with any cert.
SKIP_DIRS = {'_CodeSignature', 'SC_Info', 'PlugIns'}
SKIP_FILES = {'embedded.mobileprovision', '.DS_Store'}

CHECKS = [
    ('Driver', 0x170867C, 'e0031faa'),
    ('Driver', 0x1708684, 'e1031faa'),
    ('Driver', 0x17086BC, 'e0031faa'),
    ('Driver', 0x17086C0, 'e1031faa'),
    ('Driver', 0x1709780, '00008052c0035fd6'),
    (r'Frameworks\bshield.framework\bshield', 0x2A3868, '000080d2c0035fd6'),
    (r'Frameworks\bshield.framework\bshield', 0x1DB0EC, '000080d2c0035fd6'),
    (r'Frameworks\MDAPILayer.framework\MDAPILayer', 0x126100, '00008052c0035fd6'),
    (r'Frameworks\MDAPILayer.framework\MDAPILayer', 0x1260E0, '00008052c0035fd6'),
    (r'Frameworks\geolocator_apple.framework\geolocator_apple', 0x8080, '00008052c0035fd6'),
    (r'Frameworks\MDOrderBusiness.framework\MDOrderBusiness', 0x234840, '00008052c0035fd6'),
    (r'Frameworks\MDMap.framework\MDMap', 0x10816E0, '00008052c0035fd6'),
    (r'Frameworks\MDMap.framework\MDMap', 0x1081100, '00008052c0035fd6'),
    (r'Frameworks\build-info.framework\build-info', 0x6364, 'a83f00f0001d40f9bd671d14'),
    (r'Frameworks\build-info.framework\build-info', 0x7970, '000080d2c0035fd61f2003d5'),
    (r'Frameworks\build-info.framework\build-info', 0x760FA0, 'c0035fd6'),
    (r'Frameworks\build-info.framework\build-info', 0x2908C8, '33010014'),
    ('Driver', 0x3281C, '3f2e6394'),
    ('Driver', 0x31FA8, '37316394'),
    (r'Frameworks\build-info.framework\build-info', 0x5730, 'f10311aa'),
    (r'Frameworks\build-info.framework\build-info', 0x4174, 'f00310aaf10311aa'),
    (r'Frameworks\build-info.framework\build-info', 0xe0d0,
     'e03740f963481d94e03b00f91f2003d51f2003d51f2003d51f2003d501000014'),
    ('Driver', 0x22C740, 'c0035fd6'),
    ('Driver', 0x18FE118, '902e00d0'),
    ('Driver', 0x18FE484, '902e00d0'),
    ('Driver', 0x18FC6E8, 'a03a00d0'),
    ('Driver', 0x190C47C, '702e00d0'),
    (r'Frameworks\build-info.framework\build-info', 0x292198, '000080d2c0035fd6'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x4000, '68000090'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x5b00, 'f657bda9'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x40c4, 'ff4301d1'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x5020, '33000014'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0x40b0, '681b0014'),
    (r'Frameworks\flutter_bshield_callback.framework\flutter_bshield_callback', 0xae50,
     '280000d0089947f98802088b000140f9e00100b4290000d029e145f9e00309aa2cf8ff97e10300aae80741f8000140f9600000b4090840f920013fd6000080d2fd7b42a9f44f41a9f657c3a8c0035fd6'),
    (r'Frameworks\build-info.framework\build-info', 0x4ca80, 'f10311aa'),
    (r'Frameworks\build-info.framework\build-info', 0x75a4b0, 'f44fbea9'),

    ('Driver', 0x333cc, '2e2c6394'),
    ('Driver', 0x35e4b4, '197f5694'),
    ('Driver', 0x3b8e0c, '9e155594'),
    ('Driver', 0x5de9c8, '48774c94'),
    ('Driver', 0x32bf8, 'a03b00b4'),
    ('Driver', 0x32900, 'e8fc00f0'),
    ('Driver', 0x32918, '006b73f8'),
    ('Driver', 0x329cc, '29270e94'),
    ('Driver', 0x33398, '00fd00d0'),
    ('Driver', 0x33344, 'e00319aa'),
    ('Driver', 0x33334, 'e0031caa'),
    ('Driver', 0x3bc2c0, 'f657bda9'),
    ('Driver', 0x31e9c, 'f85fbca9'),
    ('Driver', 0x3271c, 'fc6fbaa9'),
    ('Driver', 0x246c58, 'f44fbea9'),
    ('Driver', 0x3b8da4, 'fc6fbaa9'),
    (r'Frameworks\build-info.framework\build-info', 0x4d458, '01000014'),
    (r'Frameworks\build-info.framework\build-info', 0x240040, 'fd7b41a9'),
    (r'Frameworks\build-info.framework\build-info', 0x238084, 'fd7bc1a8'),
    (r'Frameworks\build-info.framework\build-info', 0x25f2f0, 'e80300aa'),
    (r'Frameworks\build-info.framework\build-info', 0x29900, '08014239'),
    ('Driver', 0x32960, '00a941f9'),
    ('Driver', 0x32a48, '166d47f9'),
    ('Driver', 0x33374, 'bf4301d1'),
    ('Driver', 0x3336c, 'a08350f8'),
    (r'Frameworks\build-info.framework\build-info', 0x760200, 'e1040090'),
    (r'Frameworks\build-info.framework\build-info', 0x760d20, 'e1040090'),
    (r'Frameworks\build-info.framework\build-info', 0x761460, 'c10400f0'),
    (r'Frameworks\build-info.framework\build-info', 0x2910fc, '1f2003d5'),
]

def is_macho(path):
    try:
        with open(path, 'rb') as f:
            m = f.read(4)
        return m in (b'\xcf\xfa\xed\xfe', b'\xce\xfa\xed\xfe', b'\xca\xfe\xba\xbe')
    except OSError:
        return False

def cryptid(path):
    """Return LC_ENCRYPTION_INFO_64 cryptid, or None if not a thin arm64 Mach-O."""
    try:
        with open(path, 'rb') as f:
            d = f.read(0x4000)
    except OSError:
        return None
    if len(d) < 32 or struct.unpack_from('<I', d, 0)[0] != 0xfeedfacf:
        return None
    ncmds = struct.unpack_from('<I', d, 16)[0]
    o = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, o)
        if cmd == 0x2C:  # LC_ENCRYPTION_INFO_64
            return struct.unpack_from('<I', d, o + 16)[0]
        o += sz
    return 0

def main():
    pl = plistlib.load(open(os.path.join(APP, 'Info.plist'), 'rb'))
    bid = pl.get('CFBundleIdentifier')
    ver = pl.get('CFBundleShortVersionString')
    if bid != 'vn.gsm.md':
        sys.exit('bundle id is %r, expected vn.gsm.md' % bid)
    if ver != '3.19.0':
        sys.exit('version is %r, expected 3.19.0' % ver)
    print('bundle id %s  version %s' % (bid, ver))

    import json as _json
    _ec = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'expected_checks.json')
    if os.path.exists(_ec):
        CHECKS = [(e['rel'], e['off'], e['exp']) for e in _json.load(open(_ec))]
        print('using expected_checks.json (%d sites)' % len(CHECKS))
    if 'pristine' in OUT:
        print('pristine build - skipping patch verification')
    else:
        for rel, off, exp in CHECKS:
            d = open(os.path.join(APP, rel), 'rb').read()
            got = d[off:off + len(exp) // 2].hex()
            if got != exp:
                sys.exit('PATCH MISMATCH %s @0x%x: %s != %s' % (rel, off, got, exp))
        print('verified %d patch sites' % len(CHECKS))

    encrypted = []
    for root, dirs, files in os.walk(os.path.join(APP)):
        dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
        for f in files:
            full = os.path.join(root, f)
            c = cryptid(full)
            if c:
                encrypted.append(os.path.relpath(full, APP))
    if encrypted:
        sys.exit('ENCRYPTED BINARIES (FairPlay will fail):\n  ' + '\n  '.join(encrypted))
    print('verified 0 encrypted binaries')

    if os.path.exists(OUT):
        os.remove(OUT)

    count = 0
    raw = 0
    with zipfile.ZipFile(OUT, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
        for root, dirs, files in os.walk(os.path.join(SRC, 'Payload')):
            dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
            for f in sorted(files):
                if f in SKIP_FILES:
                    continue
                full = os.path.join(root, f)
                arc = os.path.relpath(full, SRC).replace('\\', '/')
                st = os.stat(full)
                info = zipfile.ZipInfo(arc, time.localtime(st.st_mtime)[:6])
                info.create_system = 3
                mode = 0o755 if is_macho(full) else 0o644
                info.external_attr = (0o100000 | mode) << 16
                info.compress_type = zipfile.ZIP_DEFLATED
                with open(full, 'rb') as fh:
                    data = fh.read()
                zf.writestr(info, data, compresslevel=6)
                count += 1
                raw += len(data)

    print('entries %d  raw %d bytes' % (count, raw))
    print('ipa size %d bytes' % os.path.getsize(OUT))
    print('sha256 %s' % hashlib.sha256(open(OUT, 'rb').read()).hexdigest())

if __name__ == '__main__':
    main()
