# sadly heavily based on code by chat-gpt
# loads the original binaries into flash and allows bigger roms to load like the pokemon games

import os

Import("env")
from SCons.Script import Builder

# read build flags (CPP defines)
flags = env.ParseFlags(env['BUILD_FLAGS'])
defs = {items[0]: items[1] for items in flags.get("CPPDEFINES", {}) if isinstance(items, list) and len(items) == 2}

# passed via -DROM_FILENAME=...
rom_filename = defs.get("ROM_FILENAME", "custom_rom.gb")

# Get the project root directory
project_root = env.Dir('#').abspath

# autogenerate original symbol names used by objcopy
auto_sym_base = rom_filename.replace(".", "_").replace(" ", "_")

# used to replace the symbol names
orig_start = f"_binary_{auto_sym_base}_start"
orig_end = f"_binary_{auto_sym_base}_end"

# your preferred symbol names
new_start = f"_binary_custom_rom_start"
new_end = f"_binary_custom_rom_end"

# Create a binary-to-object builder
bin2obj = Builder(
    action = (
        "arm-none-eabi-objcopy -I binary -O elf32-littlearm -B arm "
        "--rename-section .data=.rodata,alloc,load,readonly,data,contents "
        "--set-section-alignment .rodata=4 "
        f"--redefine-sym {orig_start}={new_start} "
        f"--redefine-sym {orig_end}={new_end} "
        "$SOURCE $TARGET"
    ),
    suffix = ".o",
    src_suffix = ".gb"
)

env.Append(BUILDERS = {"BinToObj": bin2obj})

# Convert ROM into an object file and link it in
rom_path = os.path.join(project_root, rom_filename)
rom_obj = env.BinToObj(rom_path) # produces custom_rom.gb.o
env.Append(LIBS=[rom_obj])
