#!/usr/bin/env python3
"""Set cryptid=0 for EVERY Mach-O in the app bundle (the memory-image copies all
carry the original App Store header with cryptid=1, but their content is already
decrypted)."""
import os, sys, struct

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

APP = r'E:\ios\work319\patch_src\Payload\Driver.app'
fixed, skipped = [], []
for root, dirs, files in os.walk(APP):
    for fn in files:
        p = os.path.join(root, fn)
        try:
            with open(p, 'rb') as f:
                head = f.read(4)
            if head != b'\xcf\xfa\xed\xfe':
                continue
            d = bytearray(open(p, 'rb').read())
            ncmds, = struct.unpack_from('<I', d, 16)
            off = 32
            cur = None
            for _ in range(ncmds):
                cmd, sz = struct.unpack_from('<II', d, off)
                if cmd == 0x2C:
                    cur = struct.unpack_from('<I', d, off + 16)[0]
                    if cur != 0:
                        struct.pack_into('<I', d, off + 16, 0)
                        open(p, 'wb').write(bytes(d))
                        fixed.append(os.path.relpath(p, APP))
                    break
                off += sz
            if cur == 0:
                skipped.append(os.path.relpath(p, APP))
        except Exception as e:
            print('err', p, e)

print('cryptid 1->0 : %d files' % len(fixed))
for f in fixed:
    print('   ', f)
print('already 0    : %d files' % len(skipped))
