# Top-level Makefile for the led_strip ESP-IDF project.
# Thin wrapper around idf.py. Runs on Linux, macOS (bash) and Windows (GNU make with cmd.exe or sh).
#
# Override any variable on the command line, for example:
#   make flash PORT=/dev/ttyUSB0      # Linux
#   make flash PORT=/dev/cu.usbmodem101   # macOS
#   make flash PORT=COM4              # Windows

ifeq ($(OS),Windows_NT)
  HOST_OS      := windows
  HOME_DIR     := $(USERPROFILE)
  DEFAULT_PORT := COM3
else
  HOST_OS  := $(shell uname -s)
  HOME_DIR := $(HOME)
  ifeq ($(HOST_OS),Darwin)
    DEFAULT_PORT := /dev/cu.usbmodem101
  else
    DEFAULT_PORT := /dev/ttyACM0
  endif
endif

IDF_PATH            ?= $(HOME_DIR)/.espressif/v6.1/esp-idf
IDF_PYTHON_ENV_PATH ?= $(HOME_DIR)/.espressif/python_env/idf6.1_py3.12_env
PORT                ?= $(DEFAULT_PORT)

export IDF_PATH
export IDF_PYTHON_ENV_PATH

# Run idf.py in a shell that has sourced ESP-IDF's environment script (sets PATH and toolchains).
ifeq ($(HOST_OS),windows)
define idf
	cmd /c "$(subst /,\,$(IDF_PATH))\export.bat && idf.py $(1)"
endef
else
define idf
	bash -c '. "$(IDF_PATH)/export.sh" >/dev/null 2>&1 && idf.py $(1)'
endef
endif

.PHONY: all build flash monitor flash-monitor menuconfig clean fullclean help

all: build

build:
	$(call idf,build)

flash: build
	$(call idf,-p $(PORT) flash)

monitor:
	$(call idf,-p $(PORT) monitor)

flash-monitor: build
	$(call idf,-p $(PORT) flash monitor)

menuconfig:
	$(call idf,menuconfig)

clean:
	$(call idf,clean)

fullclean:
	$(call idf,fullclean)

help:
	@echo Targets:
	@echo   build          Build the firmware
	@echo   flash          Build, then flash to the board on PORT
	@echo   monitor        Open the serial monitor on PORT
	@echo   flash-monitor  Build, flash, then open the serial monitor
	@echo   menuconfig     Open the project configuration menu
	@echo   clean          Remove build outputs
	@echo   fullclean      Delete the build directory entirely
	@echo   help           Show this help
