# Switch homebrew build, based on the devkitPro/switchbrew application template.
.SUFFIXES:

ifeq ($(strip $(DEVKITPRO)),)
$(error DEVKITPRO is not set; open a devkitPro shell or run build.ps1 on Windows)
endif

TOPDIR ?= $(CURDIR)

ifeq ($(wildcard $(DEVKITPRO)/libnx/switch_rules),)
$(error libnx is missing from $(DEVKITPRO); install the switch-dev group)
endif
include $(DEVKITPRO)/libnx/switch_rules

TARGET   := switchnote
BUILD    := build
SOURCES  := source third_party
INCLUDES := include third_party
ROMFS    := romfs

export APP_TITLE   := Switchnote Studio
export APP_AUTHOR  := RexiMemo!
export APP_VERSION := 0.1.51

ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE
PKG_CONFIG := $(PORTLIBS)/bin/aarch64-none-elf-pkg-config
SDL_PACKAGES := SDL2_image SDL2_ttf SDL2_mixer sdl2

CFLAGS   := -g -Wall -Wextra -O2 -ffunction-sections $(ARCH) $(DEFINES)
CFLAGS   += -D__SWITCH__ $(INCLUDE) $(shell $(PKG_CONFIG) --cflags $(SDL_PACKAGES))
CXXFLAGS := $(CFLAGS) -std=gnu++17 -fno-rtti -fno-exceptions
ASFLAGS  := -g $(ARCH)
LDFLAGS   = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS     := $(shell $(PKG_CONFIG) --static --libs $(SDL_PACKAGES)) -lnx
LIBDIRS  := $(PORTLIBS) $(LIBNX)

ifneq ($(BUILD),$(notdir $(CURDIR)))

export OUTPUT  := $(CURDIR)/$(TARGET)
export TOPDIR  := $(CURDIR)
export VPATH   := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)

CFILES   := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES   := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))

export LD     := $(CXX)
export OFILES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
                  $(foreach dir,$(LIBDIRS),-I$(dir)/include) \
                  -I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)

# libnx's NRO icon is JPEG. build.ps1 converts a root icon.png if supplied.
ifneq ($(wildcard $(TOPDIR)/icon.jpg),)
export APP_ICON := $(TOPDIR)/icon.jpg
else
export APP_ICON := $(LIBNX)/default_icon.jpg
endif

export NROFLAGS += --icon=$(APP_ICON) --nacp=$(CURDIR)/$(TARGET).nacp
export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS)

.PHONY: all clean $(BUILD)
all: $(BUILD)

$(BUILD):
	@mkdir -p $@
	@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile

clean:
	@rm -rf -- $(BUILD) $(TARGET).nro $(TARGET).nacp $(TARGET).elf $(TARGET).map

else

DEPENDS := $(OFILES:.o=.d)
ROMFS_FILES := $(shell find $(TOPDIR)/$(ROMFS) -type f)

.PHONY: all
all: $(OUTPUT).nro

$(OUTPUT).nro: $(OUTPUT).elf $(OUTPUT).nacp $(ROMFS_FILES)

$(OUTPUT).elf: $(OFILES)

-include $(DEPENDS)

endif
