#---------------------------------------------------------------------------------
# FAKE-08 for Xbox 360 as a native XEX (runs under the dashboard, started
# from Aurora/FSD), built WITHOUT the Microsoft XDK:
#   GCC 16 + newlib + libstdc++ (free60/libxenon image, libxenon itself is
#   not used) -> ELF -> xex-link (from xenon-forge) -> default.xex
#
# Run inside the free60/libxenon docker image. xex-link must be built first
# with tools/build-xex-link.sh (see README.md).
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITXENON)),)
$(error "Please set DEVKITXENON (run inside the free60/libxenon image)")
endif

XEX_LINK ?= $(CURDIR)/tools/bin/xex-link
BUILD    := build

CC       := xenon-gcc
CXX      := xenon-g++
MACH     := -m32 -mpowerpc64 -mhard-float -maltivec -fno-pic -G0 -msdata=none
INCLUDES := -I$(CURDIR)/runtime/include -I$(CURDIR)/runtime -I$(CURDIR)/sdk/include
CFLAGS   := $(MACH) -O2 -g -Wall -Wno-attributes -ffunction-sections -fdata-sections $(INCLUDES)
CXXFLAGS := $(CFLAGS) -std=gnu++17
ASFLAGS  := $(MACH) -Wa,-mppc64
LDFLAGS  := $(MACH) -nostartfiles -nostdlib -T $(CURDIR)/runtime/link.ld -Wl,--gc-sections
LIBS     := -L$(DEVKITXENON)/xenon/lib/32 -Wl,--start-group -lstdc++ -lm -lc -lgcc -Wl,--end-group

RUNTIME_SRC := runtime/crt0.S runtime/crt.c runtime/sys.c runtime/fs.c runtime/posix.c \
               runtime/video.c runtime/input.c \
               runtime/extra_imports.S sdk/thunks/ppc32.S
RUNTIME_OBJ := $(patsubst %,$(BUILD)/%.o,$(RUNTIME_SRC))

TESTS := hello fs video

.PHONY: all tests runtime clean
all: tests
runtime: $(RUNTIME_OBJ)
tests: $(foreach t,$(TESTS),$(BUILD)/tests/$(t)/default.xex)

$(BUILD)/%.S.o: %.S
	@mkdir -p $(dir $@)
	@echo [$(notdir $<)]
	@$(CC) $(ASFLAGS) -c $< -o $@
$(BUILD)/%.c.o: %.c
	@mkdir -p $(dir $@)
	@echo [$(notdir $<)]
	@$(CC) $(CFLAGS) -MMD -MP -c $< -o $@
$(BUILD)/%.cpp.o: %.cpp
	@mkdir -p $(dir $@)
	@echo [$(notdir $<)]
	@$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@

# tests/<name>/*.cpp -> build/tests/<name>/default.xex
.SECONDEXPANSION:
$(BUILD)/tests/%/app.elf: $$(addprefix $(BUILD)/,$$(addsuffix .o,$$(wildcard tests/$$*/*.cpp))) $(RUNTIME_OBJ) runtime/link.ld
	@mkdir -p $(dir $@)
	@echo linking $@
	@$(CXX) $(LDFLAGS) -Wl,-Map,$(@:.elf=.map) -o $@ $(filter %.o,$^) $(LIBS)

$(BUILD)/tests/%/default.xex: $(BUILD)/tests/%/app.elf tests/%/xex.toml
	@$(XEX_LINK) $< $@ --manifest tests/$*/xex.toml

clean:
	rm -r -f $(CURDIR)/$(BUILD)

-include $(shell find $(BUILD) -name '*.d' 2>/dev/null)

# keep the ELFs (symbols for addr2line)
.SECONDARY:
