#Not intended to be overriden
AUTO_OVERLAY_DIR = $(OUTPUT_DIR)/auto_overlay

include $(AUTO_OVERLAY_DIR)/Overlays.mk
include $(JABY_ENGINE_DIR)/mkfile/common/CustomConfigHelper.mk

JABY_ENGINE_LIB_DIR         = $(JABY_ENGINE_DIR)/lib/PSX-$(BUILD_PROFILE)/$(CUSTOM_CONFIG)
JABY_ENGINE_SUPPORT_LIB_DIR = $(JABY_ENGINE_DIR)/support/lib/PSX-$(BUILD_PROFILE)
JABY_ENGINE_SUPPORT_LIBS    = $(addprefix -l,$(SUPPORT_LIBS))
JABY_ENGINE_SUPPORT_DEPS    = $(addsuffix .a,$(addprefix $(JABY_ENGINE_SUPPORT_LIB_DIR)/lib,$(SUPPORT_LIBS)))
JABY_ENGINE_LIB_NAME        = JabyEngine_$(PSX_TV_FORMAT)

OVERLAY_TARGET = $(foreach ovl, $(OVERLAYSECTION), $(OUTPUT_DIR)/Overlay$(ovl))

#Linking rule
$(TARGET).elf: $(OBJS) $(JABY_ENGINE_LIB_DIR)/lib$(JABY_ENGINE_LIB_NAME).a $(JABY_ENGINE_SUPPORT_DEPS) $(AUTO_OVERLAY_DIR)/Overlays.ld
	$(LD) -o $(TARGET).elf $(LDFLAGS_all) $(LDFLAGS) $(OBJS) -L$(JABY_ENGINE_LIB_DIR) -L$(JABY_ENGINE_SUPPORT_LIB_DIR) -L$(AUTO_OVERLAY_DIR) -l$(JABY_ENGINE_LIB_NAME) $(LIBS) $(JABY_ENGINE_SUPPORT_LIBS)

#Strips the psexe
$(TARGET).psexe: $(TARGET).elf
	$(PREFIX)-objcopy $(addprefix -R , $(OVERLAYSECTION)) -O binary $< $@

#Create overlays
$(OVERLAY_TARGET): $(TARGET).elf
	$(PREFIX)-objcopy -j $(suffix $@) -O binary $< $@

#Create overlay makefile
$(AUTO_OVERLAY_DIR)/Overlays.mk: $(OVERLAY_CONFIG)
	@mkdir -p $(AUTO_OVERLAY_DIR)
	mkoverlay --mk-file $(AUTO_OVERLAY_DIR)/Overlays.mk --ld-script $(AUTO_OVERLAY_DIR)/Overlays.ld $<

#Rules section for default compilation and linking
all: $(TARGET).psexe $(OVERLAY_TARGET)

clean:
	rm -fr $(OUTPUT_DIR)

# For mkoverlay to function correctly this is required (otherwise Overlays.mk is not re-generated)
rebuild: clean
	$(MAKE) all
