# ========================================================== #
# Spider Runtime - ESP32 Build System                        #
# Toolchain: Espressif ESP-IDF (xtensa-esp-elf-g++)          #
# ========================================================== #

CC          := xtensa-esp-elf-g++
TARGET      := spider_esp32.elf
SRCDIR      := ../../src
BUILDDIR    := bin
TARGETDIR   := out
SRCEXT      := cpp
OBJEXT      := o

ESP_FLAGS   := -DESP32 -DSPIDER_DISTRO_MICRO -DSPIDER_OS_NONE -mlongcalls -ffunction-sections -fdata-sections -fno-exceptions -fno-rtti

CFLAGS      := -Wall -std=c++20 -DSPIDER_COMPILING $(ESP_FLAGS)
LFLAGS      := -Wl,--gc-sections -mlongcalls
INC         := -I../../src/

# Exclude desktop-only modules
EXCLUDE     := $(SRCDIR)/spider/runtime/util/Terminal.cpp \
               $(SRCDIR)/spider/runtime/debug/LiveDebug.cpp \
               $(SRCDIR)/spider/SpiderRuntime.cpp

# ESP32 specific entry point
EXTRA       := $(SRCDIR)/spider/main_esp32.cpp

SOURCES     := $(filter-out $(EXCLUDE), $(shell find $(SRCDIR) -type f -name "*.$(SRCEXT)" 2>/dev/null)) $(EXTRA)
OBJECTS     := $(patsubst $(SRCDIR)/%,$(BUILDDIR)/%,$(SOURCES:.$(SRCEXT)=.$(OBJEXT)))

all: directories $(TARGET)
	@echo "Build complete: $(TARGETDIR)/$(TARGET)"

remake: cleaner all

directories:
	@mkdir -p $(TARGETDIR)
	@mkdir -p $(BUILDDIR)

clean:
	@$(RM) -rf $(BUILDDIR)

cleaner: clean
	@$(RM) -rf $(TARGETDIR)

$(TARGET): $(OBJECTS)
	@echo "Linking $(TARGET)..."
	$(CC) $(LFLAGS) -o $(TARGETDIR)/$(TARGET) $^
	@echo "Done!"

$(BUILDDIR)/%.$(OBJEXT): $(SRCDIR)/%.$(SRCEXT)
	@mkdir -p $(dir $@)
	@echo "Compiling $<..."
	$(CC) $(CFLAGS) $(INC) -c -o $@ $<

.PHONY: all remake clean cleaner
