#!/usr/bin/env python3
"""Build Perfect Dark stage setup files with clang + lld instead of a MIPS gcc.

A setup file (src/setups/<name>.c) is pure data: the props/intro/paths/ailists
tables and nothing else. The Makefile turns it into a file with

    $(CC) -c  ->  tools/mksimpleelf (ld -T ld/zero.ld)  ->  objcopy -O binary  ->  tools/rarezip

which needs a mips-elf gcc toolchain and the patched gzip in tools/gzip. clang
carries a MIPS backend, lld links elf32-bigmips, and llvm-objcopy strips it, so
the whole thing runs on a stock `brew install llvm lld` with no docker and no
cross-gcc. This script is that pipeline, plus the enum headers under
src/generated/<romid> that the setups include (generated straight from the
asset json, skipping the assetmgr object/zip steps).

Verified 2026-09-21 against ntsc-final with clang 18 / lld 18: every setup the
fork has not modified is byte-identical to the file in the ROM, and every
fojo-modified setup is byte-identical to the gcc build it replaces. Three
things make that true and are easy to break:

  1. gcc on mips/o32 raises the alignment of arrays whose natural alignment is
     below 4 (u8/s8/u16/s16 tables, ie every ailist) to 4 bytes. clang packs
     them. shim() adds aligned(4) to those definitions before compiling.
  2. clang emits string literals into .rodata.str1.1 regardless of
     -fno-merge-constants; ld/zero-lld.ld widens the input rule to .rodata.*.
  3. lld synthesises a MIPS .got; zero-lld.ld discards it.

Works from either tree. In pd-fojo-n64 it uses the decomp headers as-is. In
pd-fojo (the PC port) it detects port/include and compiles against the port's
headers with the host-facing bits neutralised (-D__i386__ for platform.h,
-nostdinc plus stub libc headers for os_libc.h/fs.h) so the same setup
sources build there; measured 2026-09-21: the port-tree build of the fojo
setups is byte-identical to the n64-tree build of the same sources.

Usage, from the tree root:

    tools/mksetups                          # every setup, ROMID from env or ntsc-final
    tools/mksetups setupame mp_setupame     # just these
    tools/mksetups --patches --mod-dir basedir/data/mods/mod_fojo setupame
                                            # and ship it as a per-file xdelta
--patches is how a modified setup SHIPS: not the setup (which is Rare's data
with the edits inside) but an xdelta of the inflated bytes against the vanilla
file inflated out of the player's own ROM, applied by the engine after inflate
(PDFT v5 patch rows, port/src/romdata.c romdataFileApplyPatch). It writes
<mod-dir>/patches/U<name>Z.xdelta and upserts the manifest row
    { "name": "U<name>Z", "replaces": "U<name>Z", "patch": "patches/U<name>Z.xdelta" }
in <mod-dir>/<modname>_filetable.json. A build identical to the vanilla file
gets no patch and no row (--skip-unchanged is the default with --patches; a
setup nobody modified is already in the ROM). Run tools/mkfiletable afterwards,
or let cmake's pd_setups target do both. The ROM is --rom, else
pd.<romid>.z64 in the mod's basedir data dir or its roms/ - never $PD_ROMFILE.
AUTHORING DEPENDENCY: xdelta3 (brew install xdelta / apt install xdelta3),
dev-side only, never a player dependency. The engine carries its own decoder.

Outputs land like the Makefile's: build/<romid>/files/setup/<name>.bin (raw)
and build/<romid>/assets/files/U<name>Z (1173-compressed). --out copies the
compressed files somewhere else as well, eg a moddir's files/.

Compression is python zlib raw deflate, not tools/gzip. The bytes differ from
Rare's gzip but inflate to the same file; the port's romdata.c and the N64's
rzip only care about the 1173 header and the payload. If you need a matching
ROM, use the Makefile.

Tool lookup: $LLVM_BIN / $LLD_BIN, else the homebrew llvm and lld formula dirs,
else PATH. Two formulae on the mac: `brew install llvm lld` (lld is separate).
"""

import argparse
import glob
import json
import os
import re
import shutil
import subprocess
import sys
import zlib

VERSIONS = {
    'ntsc-beta': 0, 'ntsc-1.0': 1, 'ntsc-final': 2,
    'pal-beta': 3, 'pal-final': 4, 'jpn-final': 5,
}

CFLAGS = [
    '--target=mips-unknown-elf', '-mcpu=mips3', '-mabi=32', '-EB',
    '-mno-abicalls', '-G0',
    '-ffreestanding', '-fno-builtin', '-fno-common', '-fno-merge-constants',
    '-fno-zero-initialized-in-bss', '-funsigned-char', '-fwrapv',
    '-Os', '-w',
    # mips-gcc predefines these; ultratypes.h hides u8/s32/... without them
    '-D_LANGUAGE_C', '-D_MIPS_SZLONG=32', '-D_MIPS_SZINT=32',
]

# gcc raises arrays with natural alignment < 4 to 4. Only top-level
# definitions of byte/halfword arrays; struct arrays and s32/u32 are already
# word aligned and gcc leaves them alone (aligned(8) everywhere was tried and
# is wrong).
SHIM_RE = re.compile(r'^((?:u8|s8|u16|s16|char) [A-Za-z0-9_]+\[[^\]]*\]) = \{', re.M)


TOOLS = {
    # tool: (homebrew formula that carries it). homebrew's llvm formula no
    # longer bundles lld; ld.lld comes from its own `lld` formula.
    'clang': 'llvm',
    'llvm-objcopy': 'llvm',
    'ld.lld': 'lld',
}

SEARCH_DIRS = [
    os.environ.get('LLVM_BIN'),
    os.environ.get('LLD_BIN'),
    '/opt/homebrew/opt/llvm/bin', '/opt/homebrew/opt/lld/bin',
    '/usr/local/opt/llvm/bin', '/usr/local/opt/lld/bin',
]


def find_llvm():
    """Map each tool name to a path, looking in the well-known brew dirs
    first, then PATH. Apple's clang has no MIPS backend and Xcode has no lld,
    so PATH is the fallback, not the first choice."""
    found = {}
    missing = []
    for tool, formula in TOOLS.items():
        for d in SEARCH_DIRS:
            if d and os.path.exists(os.path.join(d, tool)):
                found[tool] = os.path.join(d, tool)
                break
        else:
            p = shutil.which(tool)
            if p:
                found[tool] = p
            else:
                missing.append('%s (brew install %s, or set %s)' % (
                    tool, formula, 'LLD_BIN' if formula == 'lld' else 'LLVM_BIN'))
    if missing:
        sys.exit('mksetups: not found: ' + '; '.join(missing))
    return found


def write_enums(romid, typename, names, filename, terminator, start=0):
    # same output as tools/assetmgr/assetmgr.py write_enums, without importing
    # it (assetmgr.zip wants tools/gzip built)
    path = os.path.join('src/generated', romid, filename)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w') as fd:
        fd.write('/**\n * This file was generated automatically. Changes may be overwritten.\n */\n\n')
        fd.write('enum %s {\n' % typename)
        for index, name in enumerate(names):
            if index == 0 and start != 0:
                fd.write('\t%s = %d,\n' % (name, start))
            else:
                fd.write('\t%s,\n' % name)
        fd.write('\t%s,\n' % terminator)
        fd.write('};\n')


def gen_headers(romid):
    A = 'src/assets/%s/' % romid
    W = lambda *a, **k: write_enums(romid, *a, **k)
    W('animnum', [r['id'] for r in json.load(open(A + 'animations.json'))], 'animations.h', 'ANIM_END')
    W('music', [r['id'] for r in json.load(open(A + 'sequences.json'))], 'sequences.h', 'MUSIC_END')
    W('texturenum', [r['id'] for r in json.load(open(A + 'textures.json'))], 'textures.h', 'TEXTURE_END')
    for j in sorted(glob.glob(A + 'pads/*.json')):
        s = os.path.basename(j)[:-5]
        W('pad_%s' % s, [r['id'] for r in json.load(open(j))['pads']], 'pads/%s.h' % s, 'PAD_%s_END' % s.upper())
    for j in sorted(glob.glob(A + 'tiles/*.json')):
        s = os.path.basename(j)[:-5]
        W('room_%s' % s, list(json.load(open(j))['rooms'].keys()), 'tiles/%s.h' % s, 'ROOM_%s_END' % s.upper())
    banks = eval(re.search(r'banks\s*=\s*(\[[^\]]*\])', open('tools/assetmgr/mklang').read(), re.S).group(1))
    for j in sorted(glob.glob(A + 'lang/*.json')):
        s = re.match(r'^[a-z0-9]+', os.path.basename(j))[0]
        if s in banks:
            W('l_%s' % s, [r['id'] for r in json.load(open(j))], 'lang/%s.h' % s,
              'L_%s_END' % s.upper(), start=banks.index(s) * 512)


def is_port_tree():
    # the PC port tree carries the decomp under src/ plus port/; its headers
    # are host-facing (platform.h wants a host arch, os_libc.h wants a libc)
    return os.path.isdir('port/include')


def port_defines():
    # platform.h #errors on an unknown arch and the MIPS target is unknown to
    # it. __i386__ picks the 32-bit, little-endian-agnostic branch, which only
    # decides pointer width for the host structs; the data we emit is all
    # explicit-width fields and 32-bit pointers from the MIPS target anyway.
    return ['-D__i386__']


def port_includes(llvm, B):
    # -nostdinc so <stdio.h> and friends cannot reach the host's libc headers
    # (which a mips target cannot parse); clang's own resource dir supplies
    # stdint/stddef/stdarg, and a stub dir supplies empty libc headers for
    # the port headers that include them. fs.h names FILE, so stdio.h gets
    # an opaque typedef.
    stub = os.path.join(B, 'stubinc')
    os.makedirs(stub, exist_ok=True)
    for h in ('strings.h', 'string.h', 'stdlib.h', 'math.h'):
        open(os.path.join(stub, h), 'w').close()
    with open(os.path.join(stub, 'stdio.h'), 'w') as fd:
        fd.write('#include <stddef.h>\ntypedef struct _FILE FILE;\n')
    res = subprocess.check_output([llvm['clang'], '-print-resource-dir']).decode().strip()
    return ['-nostdinc', '-isystem', os.path.join(res, 'include'), '-isystem', stub,
            '-Iport/include']


def rarezip(data):
    # tools/rarezip: "1173" + 24-bit size + raw deflate. Same container, our
    # own deflate stream.
    if not data:
        return b''
    c = zlib.compressobj(9, zlib.DEFLATED, -15)
    return b'\x11\x73' + len(data).to_bytes(3, 'big') + c.compress(data) + c.flush()


def build_one(llvm, romid, name, verbose):
    version = VERSIONS[romid]
    pal = 1 if romid.startswith('pal') else 0
    B = 'build/%s' % romid
    objdir = os.path.join(B, 'assets/files/setup')
    bindir = os.path.join(B, 'files/setup')
    os.makedirs(objdir, exist_ok=True)
    os.makedirs(bindir, exist_ok=True)

    src = 'src/setups/%s.c' % name
    shimmed = os.path.join(objdir, name + '.c')
    obj = os.path.join(objdir, name + '.o')
    ld = os.path.join(objdir, name + '.ld')
    elf = os.path.join(objdir, name + '.elf')
    binp = os.path.join(bindir, name + '.bin')
    zipp = os.path.join(B, 'assets/files', 'U%sZ' % name)

    with open(src) as fd:
        text = fd.read()
    with open(shimmed, 'w') as fd:
        fd.write(SHIM_RE.sub(r'\1 __attribute__((aligned(4))) = {', text))

    defines = ['-DVERSION=%d' % version, '-DMATCHING=1', '-DPAL=%d' % pal,
               '-DPIRACYCHECKS=1', '-DROM_SIZE=32', '-DAVOID_UB']
    includes = ['-Iinclude', '-Iinclude/PR', '-Isrc/include',
                '-Isrc/generated/%s' % romid, '-Isrc/lib/ultra/audio']
    if is_port_tree():
        defines += port_defines()
        includes = port_includes(llvm, B) + includes
    cmd = [llvm['clang']] + CFLAGS + defines + includes + ['-c', shimmed, '-o', obj]
    if verbose:
        print(' '.join(cmd))
    subprocess.check_call(cmd)

    with open('ld/zero-lld.ld') as fd:
        script = fd.read().replace('__FILE__', obj)
    with open(ld, 'w') as fd:
        fd.write(script)
    subprocess.check_call([llvm['ld.lld'], '-T', ld, '-o', elf, obj],
                          stderr=subprocess.DEVNULL if not verbose else None)
    subprocess.check_call([llvm['llvm-objcopy'], '-O', 'binary', elf, binp])

    with open(binp, 'rb') as fd:
        raw = fd.read()
    with open(zipp, 'wb') as fd:
        fd.write(rarezip(raw))
    return binp, zipp, len(raw)


def main():
    ap = argparse.ArgumentParser(description='build stage setup files with clang/lld')
    ap.add_argument('names', nargs='*', help='setup names (src/setups/<name>.c); default all')
    ap.add_argument('--romid', default=os.environ.get('ROMID', 'ntsc-final'), choices=sorted(VERSIONS))
    ap.add_argument('--out', help='also copy the compressed U<name>Z files into this dir (eg a moddir files/)')
    ap.add_argument('--no-headers', action='store_true', help='skip regenerating src/generated/<romid>')
    ap.add_argument('-v', '--verbose', action='store_true')
    ap.add_argument('--patches', action='store_true',
                    help='write <mod-dir>/patches/U<name>Z.xdelta against the vanilla file and upsert the manifest rows')
    ap.add_argument('--mod-dir', help='the mod directory (data/mods/<name>); its folder name is the mod name')
    ap.add_argument('--rom', help='the base ROM to diff against (default: pd.<romid>.z64 in the mod\'s basedir data/ or data/roms/)')
    ap.add_argument('--xdelta3', default=os.environ.get('XDELTA3', 'xdelta3'))
    ap.add_argument('--keep-unchanged', action='store_true',
                    help='with --patches: write an (empty) patch and a row even for a build identical to vanilla')
    args = ap.parse_args()

    if args.patches and not args.mod_dir:
        sys.exit('mksetups: --patches needs --mod-dir')

    if not os.path.isdir('src/setups'):
        sys.exit('mksetups: run from the pd-fojo-n64 root (no src/setups here)')
    llvm = find_llvm()
    if not args.no_headers:
        gen_headers(args.romid)

    names = args.names or sorted(os.path.basename(p)[:-2] for p in glob.glob('src/setups/*.c'))
    if args.out:
        os.makedirs(args.out, exist_ok=True)
    failed = 0
    built = []
    for name in names:
        try:
            binp, zipp, size = build_one(llvm, args.romid, name, args.verbose)
        except subprocess.CalledProcessError as e:
            print('FAIL %s: %s' % (name, e))
            failed += 1
            continue
        line = '%s %d' % (binp, size)
        if args.out:
            dst = os.path.join(args.out, os.path.basename(zipp))
            shutil.copyfile(zipp, dst)
            line += ' -> ' + dst
        print(line)
        built.append((name, binp))
    if failed:
        sys.exit(1)
    if args.patches:
        write_patches(args, built)


def find_rom(args):
    """The base ROM: --rom, else pd.<romid>.z64 in the mod's basedir data dir
    (data/, data/roms/) - the same places the engine looks. Not $PD_ROMFILE:
    that is the installed game's rom, and a build reads only its own tree."""
    if args.rom:
        if not os.path.isfile(args.rom):
            sys.exit('mksetups: --rom %s: no such file' % args.rom)
        return args.rom
    data = os.path.abspath(os.path.join(args.mod_dir, '..', '..'))
    fn = 'pd.%s.z64' % args.romid
    for c in (os.path.join(data, fn), os.path.join(data, 'roms', fn)):
        if os.path.isfile(c):
            return c
    sys.exit('mksetups: no base ROM: put %s in %s (or %s/roms), or pass --rom' % (fn, data, data))


def write_patches(args, built):
    import tempfile
    xd = shutil.which(args.xdelta3)
    if not xd:
        sys.exit('mksetups: no xdelta3 on PATH (brew install xdelta / apt install xdelta3), or pass --xdelta3')
    here = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, os.path.join(here, 'lib', 'packages', 'python'))
    from leylinelib.pd_rom_driver import PDROMDriver
    rom_path = find_rom(args)
    rom = open(rom_path, 'rb').read()
    driver = PDROMDriver(rom_path=rom_path)
    vanilla = {f['name']: f for f in driver.get_files()}

    def inflate1173(b):
        if len(b) < 5 or b[:2] != b'\x11\x73':
            return bytes(b)
        return zlib.decompress(b[5:], -15)

    mod_dir = os.path.abspath(args.mod_dir)
    mod_name = os.path.basename(mod_dir)
    patches_dir = os.path.join(mod_dir, 'patches')
    os.makedirs(patches_dir, exist_ok=True)
    rows = []
    with tempfile.TemporaryDirectory() as tmp:
        for name, binp in built:
            romname = 'U%sZ' % name
            if romname not in vanilla:
                sys.exit('mksetups: %s is not a file in %s' % (romname, os.path.basename(rom_path)))
            f = vanilla[romname]
            van = inflate1173(rom[f['offset']:f['end_offset']])
            raw = open(binp, 'rb').read()
            if raw == van and not args.keep_unchanged:
                print('%s: identical to the vanilla file, no patch' % romname)
                continue
            van_path = os.path.join(tmp, romname + '.vanilla.bin')
            open(van_path, 'wb').write(van)
            out = os.path.join(patches_dir, romname + '.xdelta')
            # -A drops the application header: it carries the source and
            # target FILENAMES, i.e. a tempdir path, so without it the same
            # bytes patched twice gave two different xdeltas and every
            # cmake run churned 17 binaries in git. The engine never reads it.
            subprocess.check_call([xd, '-e', '-A', '-S', 'none', '-f', '-s', van_path, binp, out])
            print('%s: %d -> %d bytes, patch %d B -> patches/%s.xdelta' % (
                romname, len(van), len(raw), os.path.getsize(out), romname))
            rows.append((romname, 'patches/%s.xdelta' % romname))
    if not rows:
        return
    manifest_path = os.path.join(mod_dir, '%s_filetable.json' % mod_name)
    if os.path.isfile(manifest_path):
        with open(manifest_path) as fd:
            manifest = json.load(fd)
    else:
        manifest = {'modName': mod_name, 'files': []}
    files = manifest.setdefault('files', [])
    by_name = dict((e.get('name'), e) for e in files if isinstance(e, dict))
    for romname, rel in rows:
        row = by_name.get(romname)
        if row is None:
            row = {'name': romname}
            files.append(row)
            by_name[romname] = row
        row['replaces'] = romname
        row['patch'] = rel
        row.pop('path', None)
        row.pop('prefix', None)
        row.setdefault('description', "%s, patched after inflate against the player's own ROM" % romname)
    with open(manifest_path, 'w') as fd:
        json.dump(manifest, fd, indent=2, ensure_ascii=False)
        fd.write('\n')
    print('updated %s (%d patched rows); now rebuild filetable.dat:' % (manifest_path, len(rows)))
    print('    tools/mkfiletable/mkfiletable %s --workspace %s --output %s --rom-dir %s' % (
        mod_name, mod_dir, mod_dir, os.path.dirname(rom_path)))


if __name__ == '__main__':
    main()
