#!/usr/bin/env python3
"""The properly-dumped Driver carries the App Store header, so cryptid is still 1.
Our copy is already decrypted, so cryptid must be 0 or iOS refuses to run it."""
import struct, sys

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

for path in (r'E:\ios\work319\patch_src\Payload\Driver.app\Driver',
             r'E:\ios\work319\patch_src\Payload\Driver.app\Frameworks\build-info.framework\build-info'):
    d = bytearray(open(path, 'rb').read())
    if struct.unpack_from('<I', d, 0)[0] != 0xFEEDFACF:
        print('%s : not Mach-O' % path)
        continue
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    changed = False
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:  # LC_ENCRYPTION_INFO_64
            off_in_cmd = off + 16
            cur = struct.unpack_from('<I', d, off_in_cmd)[0]
            if cur != 0:
                struct.pack_into('<I', d, off_in_cmd, 0)
                changed = True
                print('%s : cryptid %d -> 0 (cmd at 0x%x)' % (path.split("\\")[-1], cur, off))
            else:
                print('%s : cryptid already 0' % path.split("\\")[-1])
        off += sz
    if changed:
        open(path, 'wb').write(bytes(d))
