# Cheevotron Pocket firmware.
#   make host-test    builds fw/host/settest natively and runs every GB/GBC set test (needs the TSVs from
#                     cheevotron's sets/tools/build.mjs in $(SETS))
# Tools: MSYS2 ucrt64 gcc for the host build.

RC_UP   := third_party/rcheevos
# rcheevos as the firmware builds it: the upstream submodule with our patches (patches/rcheevos-*.patch, each one
# keeps rcheevos' results identical; see the patch headers), copied and patched into build/rcheevos
RC      := build/rcheevos
RC_PATCHES := $(sort $(wildcard patches/rcheevos-*.patch))
ifneq ($(filter build/%,$(RC)),$(RC))
$(error RC must be a folder under build/ (the patched copy is deleted and made again), not $(RC))
endif
SETS    ?= ../../cheevotron/sets/build
HOSTCC  ?= gcc
BUILD   := build
PYTHON  ?= python

RC_SRC  := $(patsubst $(RC_UP)/%,$(RC)/%,$(wildcard $(RC_UP)/src/rcheevos/*.c)) $(RC)/src/rc_util.c $(RC)/src/rc_compat.c $(RC)/src/rhash/md5.c
RC_INC  := -I$(RC)/include -I$(RC)/src
COMMON  := common/gbmap.c common/chv_eval.c

HOSTFLAGS := -O2 -g -Wall -Wno-unused-function -DRC_NO_THREADS $(RC_INC) -Icommon

# MSYS2's make hands native compilers no usable TMP, so they fall back to C:\Windows
ifneq ($(shell command -v cygpath 2>/dev/null),)
export TMP := $(shell cygpath -w /tmp)
export TEMP := $(TMP)
endif

$(RC)/.patched: $(RC_PATCHES) $(wildcard $(RC_UP)/src/*.c $(RC_UP)/src/*/*.c $(RC_UP)/src/*/*.h $(RC_UP)/include/*.h)
	rm -rf $(RC) && mkdir -p $(RC) && cp -r $(RC_UP)/include $(RC_UP)/src $(RC)/
	for p in $(RC_PATCHES); do patch -s -p0 -d $(RC) < $$p || exit 1; done
	touch $@
$(RC_SRC): $(RC)/.patched

# ---- soft CPU (PicoRV32 in the core) ----
CROSS   ?= riscv32-unknown-elf-
ARCH    ?= rv32imc
OPT     ?= -O2
FW_OPT  ?= -O2
# the firmware's first log line names its build (seconds since 1970 when it was built)
FW_STAMP ?= $(shell date +%s)
TFLAGS  := -march=$(ARCH) -mabi=ilp32 $(OPT) -g -ffunction-sections -fdata-sections -fno-common \
           -Wall -Wno-unused-function -Wno-format -DRC_NO_THREADS -DNDEBUG $(RC_INC) -Icommon
TLDFLAGS := -nostartfiles -specs=nano.specs -Wl,--gc-sections -Ttarget/link.ld
# nano.specs turns -lm into the missing libm_nano; libm itself is fine with newlib-nano
LIBM     = $(shell $(CROSS)gcc -march=$(ARCH) -mabi=ilp32 -print-file-name=libm.a)
TARGET_RT := target/crt0.S target/syscalls.c
RC_TSRC   := $(filter-out %/rc_validate.c %/consoleinfo.c,$(RC_SRC))

# Speed gate: make bench BENCH_TSV=<tsv> BENCH_HASH=<hash prefix> BENCH_NAME=<label>
BENCH_TSV  ?= $(SETS)/pokemon-pinball.tsv
BENCH_HASH ?= fbe20570
BENCH_NAME ?= pinball
BENCH_DIR  := $(BUILD)/bench/$(BENCH_NAME)-$(ARCH)

$(BENCH_DIR)/bench_logic.h: $(BENCH_TSV) bench/gen_logic.awk
	@mkdir -p $(BENCH_DIR)
	awk -v hash=$(BENCH_HASH) -v name=$(BENCH_NAME) -f bench/gen_logic.awk $(BENCH_TSV) > $@

$(BENCH_DIR)/bench.elf: bench/bench.c $(BENCH_DIR)/bench_logic.h $(COMMON) $(RC_TSRC) $(TARGET_RT) target/link.ld
	$(CROSS)gcc $(TFLAGS) -I$(BENCH_DIR) $(TLDFLAGS) -o $@ $(TARGET_RT) bench/bench.c $(COMMON) $(RC_TSRC) $(LIBM)
	$(CROSS)size $@

$(BENCH_DIR)/bench.hex: $(BENCH_DIR)/bench.elf
	$(CROSS)objcopy -O verilog --verilog-data-width=4 $< $@

bench: $(BENCH_DIR)/bench.hex

# ---- boot ROM (8 KiB at 0x7000_0000; its last 64 bytes are the key words, zero since per-Pocket keys) ----
BOOT_KEY ?= none
$(BUILD)/boot/boot.elf: boot/start.S boot/boot.c common/crypto.c common/crypto.h common/chv_hw.h boot/boot.ld
	@mkdir -p $(BUILD)/boot
	$(CROSS)gcc -march=rv32im_zicsr_zifencei -mabi=ilp32 -Os -g -ffreestanding -nostdlib -fno-builtin-memcpy -fno-delete-null-pointer-checks -ffunction-sections \
	  -fdata-sections -Wall -Icommon $(BOOT_DEFS) -Wl,--gc-sections -Tboot/boot.ld -o $@ boot/start.S boot/boot.c common/crypto.c -lgcc
	$(CROSS)size $@

$(BUILD)/boot/bootrom.hex: $(BUILD)/boot/boot.elf $(filter-out none,$(BOOT_KEY)) ../tools/mkbootrom.py
	$(CROSS)objcopy -O binary -j .text -j .rodata $< $(BUILD)/boot/boot.bin
	$(PYTHON) -I ../tools/mkbootrom.py $(BUILD)/boot/boot.bin $(BOOT_KEY) $(BUILD)/boot/bootrom

bootrom: $(BUILD)/boot/bootrom.hex

# ---- firmware (cheevotron.fw: header + image loaded at SRAM 0 by the boot ROM) ----
FW_SRC := main/start.S main/main.c main/plat.c main/popup.c main/list.c main/cart.c main/hashcache.c main/rom_gba.c main/font.c main/syscalls.c bench/fw_bench.c \
          common/gbmap.c common/chv_eval.c common/pack.c common/crypto.c common/speedrun.c $(RC_TSRC)
$(BUILD)/fw/fw.elf: $(FW_SRC) main/*.h common/*.h bench/*.h main/link.ld
	@mkdir -p $(BUILD)/fw
	$(CROSS)gcc -march=rv32im_zicsr -mabi=ilp32 $(FW_OPT) -g -ffunction-sections -fdata-sections -fno-common -Wall \
	  -Wno-unused-function -Wno-format -DRC_NO_THREADS -DRC_HOT_ALLOC -DNDEBUG -DCHV_BUILD_STAMP=$(FW_STAMP)u $(FW_DEFS) $(RC_INC) -Icommon -Imain -Ibench \
	  -nostartfiles -specs=nano.specs -Wl,--gc-sections -Tmain/link.ld -o $@ $(FW_SRC) \
	  $(shell $(CROSS)gcc -march=rv32im -mabi=ilp32 -print-file-name=libm.a)
	$(CROSS)size $@

$(BUILD)/fw/cheevotron.fw: $(BUILD)/fw/fw.elf ../tools/mkfw.py
	$(CROSS)objcopy -O binary -j .text -j .rodata -j .data $< $(BUILD)/fw/fw.bin
	$(PYTHON) -I ../tools/mkfw.py $< $(BUILD)/fw/fw.bin $@

fw: $(BUILD)/fw/cheevotron.fw

# the GBA core's firmware: same sources with CHV_GBA (GBA memory map, ROM MD5 in software)
fw-gba:
	$(MAKE) fw BUILD=$(BUILD)/gba FW_DEFS="$(FW_DEFS) -DCHV_GBA"

.PHONY: host-test holdtest packtest bench bootrom fw fw-gba clean

$(BUILD)/host/settest.exe: host/settest.c $(COMMON) $(RC_SRC) common/*.h
	@mkdir -p $(BUILD)/host
	$(HOSTCC) $(HOSTFLAGS) -o $@ host/settest.c $(COMMON) $(RC_SRC)

# the firmware's pack, record and speedrun code against a server pack (cheevotron/server/test/pocket.mjs runs it)
packtest: $(BUILD)/host/packtest.exe
$(BUILD)/host/packtest.exe: host/packtest.c common/pack.c common/crypto.c common/speedrun.c common/*.h
	@mkdir -p $(BUILD)/host
	$(HOSTCC) -O2 -Wall -Icommon -o $@ host/packtest.c common/pack.c common/crypto.c common/speedrun.c -lm

# holding achievements back until an EEPROM cartridge's save is copied (host/holdtest.c), on the patched rcheevos
holdtest: $(BUILD)/host/holdtest.exe
	$(BUILD)/host/holdtest.exe
$(BUILD)/host/holdtest.exe: host/holdtest.c $(COMMON) $(RC_SRC) common/*.h
	@mkdir -p $(BUILD)/host
	$(HOSTCC) $(HOSTFLAGS) -DNDEBUG -o $@ host/holdtest.c $(COMMON) $(RC_SRC)

host-test: $(BUILD)/host/settest.exe
	$(BUILD)/host/settest.exe $(sort $(wildcard $(SETS)/*.tsv))

# rcheevos patches change nothing: every set (tools/seed_sets.py), 300 frames of changing memory, through the upstream
# rcheevos and through the patched copy; the traces (unlocks and a hash of the whole progress state per frame) must match
EQUIV_SETS ?= $(BUILD)/host/all_sets.tsv
RC_UP_SRC := $(wildcard $(RC_UP)/src/rcheevos/*.c) $(RC_UP)/src/rc_util.c $(RC_UP)/src/rc_compat.c $(RC_UP)/src/rhash/md5.c
$(BUILD)/host/equiv_up.exe: host/equiv.c $(COMMON) common/*.h
	@mkdir -p $(BUILD)/host
	$(HOSTCC) -O2 -DRC_NO_THREADS -DNDEBUG -I$(RC_UP)/include -I$(RC_UP)/src -Icommon -o $@ host/equiv.c $(COMMON) $(RC_UP_SRC)
$(BUILD)/host/equiv.exe: host/equiv.c $(COMMON) $(RC_SRC) common/*.h
	@mkdir -p $(BUILD)/host
	$(HOSTCC) -O2 -DRC_NO_THREADS -DNDEBUG $(RC_INC) -Icommon -o $@ host/equiv.c $(COMMON) $(RC_SRC)
$(EQUIV_SETS):
	@mkdir -p $(BUILD)/host
	$(PYTHON) ../tools/seed_sets.py $@
equiv-test: $(BUILD)/host/equiv_up.exe $(BUILD)/host/equiv.exe $(EQUIV_SETS)
	$(BUILD)/host/equiv_up.exe $(EQUIV_SETS) 300 > $(BUILD)/host/trace_up.txt
	$(BUILD)/host/equiv.exe $(EQUIV_SETS) 300 > $(BUILD)/host/trace_patched.txt
	cmp $(BUILD)/host/trace_up.txt $(BUILD)/host/trace_patched.txt
	@echo "equivalent: $$(grep -c '^set' $(BUILD)/host/trace_up.txt) sets, $$(grep -c ' u' $(BUILD)/host/trace_up.txt) frames with unlocks"

clean:
	rm -rf $(BUILD)
