#!/usr/bin/env python3
"""Gộp nhiều lát Mach-O thành một fat binary (thay cho llvm-lipo).

Dùng: python make_fat.py <output> <slice1> <slice2> ...
Hỗ trợ arm64 (0x0100000C) và arm64e (0x0100000C / 0x80000002).
"""

import struct
import sys

FAT_MAGIC = 0xCAFEBABE
MH_MAGIC_64 = 0xFEEDFACF
CPU_TYPE_ARM64 = 0x0100000C
CPU_SUBTYPE_MASK = 0xFF000000
CPU_SUBTYPE_ARM64E = 2
ALIGN = 14  # 16 KiB, giống lipo của Apple


def read_slice(path):
    with open(path, "rb") as handle:
        data = handle.read()

    if len(data) < 32:
        raise SystemExit(f"{path}: file quá nhỏ")

    magic = struct.unpack(">I", data[:4])[0]
    if magic == FAT_MAGIC:
        raise SystemExit(f"{path}: đã là fat binary, không cần gộp")

    magic_le = struct.unpack("<I", data[:4])[0]
    if magic_le != MH_MAGIC_64:
        raise SystemExit(f"{path}: không phải Mach-O 64-bit (magic=0x{magic_le:08X})")

    cputype, cpusubtype = struct.unpack("<II", data[4:12])
    return data, cputype, cpusubtype


def main():
    if len(sys.argv) < 3:
        raise SystemExit("Dùng: python make_fat.py <output> <slice1> <slice2> ...")

    output = sys.argv[1]
    inputs = sys.argv[2:]

    slices = []
    for path in inputs:
        data, cputype, cpusubtype = read_slice(path)
        slices.append((cputype, cpusubtype, data, path))
        subtype = cpusubtype & ~CPU_SUBTYPE_MASK
        name = "arm64e" if subtype == CPU_SUBTYPE_ARM64E else "arm64"
        print(f"  + {path}: {name} ({len(data)} bytes)")

    # Chống trùng kiến trúc.
    seen = set()
    for cputype, cpusubtype, _, path in slices:
        key = (cputype, cpusubtype)
        if key in seen:
            raise SystemExit(f"Trùng kiến trúc: {path}")
        seen.add(key)

    align_size = 1 << ALIGN
    offset = align_size
    entries = []

    for cputype, cpusubtype, data, _ in slices:
        padded = (len(data) + align_size - 1) & ~(align_size - 1)
        entries.append((cputype, cpusubtype, offset, len(data), ALIGN))
        offset += padded

    with open(output, "wb") as handle:
        handle.write(struct.pack(">II", FAT_MAGIC, len(entries)))
        for cputype, cpusubtype, off, size, align in entries:
            handle.write(struct.pack(">IIIII", cputype, cpusubtype & 0xFFFFFFFF, off, size, align))

        header_end = 8 + 20 * len(entries)
        handle.write(b"\x00" * (align_size - header_end))

        for index, (_, _, data, _) in enumerate(slices):
            target = entries[index][2]
            handle.seek(target)
            handle.write(data)
            padded = (len(data) + align_size - 1) & ~(align_size - 1)
            handle.write(b"\x00" * (padded - len(data)))

    print(f"  => {output} ({offset} bytes)")


if __name__ == "__main__":
    main()
