# Compiler
CXX		:= g++
CFLAGS  := -Wall -Wextra -O2 -Wno-unused -std=c++17

TARGET	    := SQLinkLogger

# Directory definitions
SRCDIR		:= src
BUILDDIR	:= build
BINDIR      := bin
LOGDIR      := logs


# Files tracking
#SOURCES		:= $(wildcard $(SRCDIR)/.cpp)
SOURCES			:= $(SRCDIR)/main.cpp
OBJECTS			:= $(SOURCES:.cpp=.o))
BIN				?= ../$(BINDIR)/
LOGS			:= ../$(LOGDIR)/

# OBJECTS		:= $(patsubst $(SRCDIR)/%.cpp,$(BUILDDIR)/%.o,$(SOURCES))

# Build rules
all: $(TARGET)

# Linking
$(TARGET): $(SOURCES)
	$(CXX) $(CFLAGS) $< -o $@

# Compiling
%.o: $(SRCDIR)/%.cpp | $(BUILDDIR)
	$(CXX) -c $< -o $@

# Create build dir if it doesnt exist
$(BUILDDIR):
	mkdir -p $(BUILDDIR)

# Clean statement
clean:
	rm -rf $(BUILDDIR) $(TARGET)

# Run Logger
run:
	./$(TARGET)


# Flash configuration
PORT		?= /dev/ttyACM8
ESPTOOL		?= esptool
BAUD		?= 921600

# Optional per-device folder produced by Bridge postbuild.py:
#   make flash DEVICE=demeter_2 /dev/ESP32S3_5B90153402
# Without DEVICE, bins still come from flat ../bin/ (manual workflow).
DEVICE		?=
ifneq ($(DEVICE),)
  BIN := ../$(BINDIR)/$(DEVICE)/
endif

# boot_app0.bin is shared at bin root (not uploaded per device)
BOOT_APP0	?= ../$(BINDIR)/boot_app0.bin

# Usage :
# ls -l /dev/E*
# make flash /dev/ESP32S3_5A7A048466
# make flash DEVICE=demeter_2 /dev/ESP32S3_5B90153402

flash:
	$(eval RAW_PORT := $(word 2,$(MAKECMDGOALS)))
	$(eval PORT := $(if $(filter /dev/%,$(RAW_PORT)),$(RAW_PORT),/dev/$(RAW_PORT)))
	@echo "Flashing $(PORT) from $(BIN)"
	$(ESPTOOL) --chip esp32s3 --port $(PORT) --baud $(BAUD) --before default_reset --after hard_reset -v write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0x0 $(BIN)bootloader.bin 0x8000 $(BIN)partitions.bin 0xE000 $(BOOT_APP0) 0x10000 $(BIN)firmware.bin


flashp4:
	$(eval RAW_PORT := $(word 2,$(MAKECMDGOALS)))
	$(eval PORT := $(if $(filter /dev/%,$(RAW_PORT)),$(RAW_PORT),/dev/$(RAW_PORT)))
	@echo "Flashing $(PORT) from $(BIN)"
	$(ESPTOOL) --chip esp32p4 --port $(PORT) --baud $(BAUD) --before default-reset --after hard-reset write-flash -z --flash-mode dio --flash-freq 80m --flash-size detect 0x2000 $(BIN)bootloader.bin 0x8000 $(BIN)partitions.bin 0xe000 $(BOOT_APP0) 0x10000 $(BIN)firmware.bin

# Swallow extra goal so: make flash /dev/ESP32S3_xxx
%:
	@:

cl:
	@echo "Cleaning all logs files"
	rm $(LOGS)*

.PHONY: all clean flash run cleanlog
