IDF_PATH := $(HOME)/.espressif/v6.0/esp-idf
PORT     := $(or $(ESP_PORT),$(shell cat .espport 2>/dev/null),/dev/cu.usbmodem1101)

export IDF_PYTHON_ENV_PATH := $(HOME)/.espressif/python_env/idf6.0_py3.12_env

IDF = . $(IDF_PATH)/export.sh > /dev/null 2>&1 && idf.py

.PHONY: all flash monitor clean menuconfig size erase select fcf

all:
	$(IDF) build

flash:
	$(IDF) -p $(PORT) flash

monitor:
	$(IDF) -p $(PORT) monitor

clean:
	$(IDF) fullclean

menuconfig:
	$(IDF) menuconfig

size:
	$(IDF) size

erase:
	$(IDF) -p $(PORT) erase-flash

fcf:
	rm -rf build sdkconfig
	$(IDF) -p $(PORT) flash monitor

select:
	@devs=($$(ls /dev/cu.usb* 2>/dev/null)); \
	if [ $${#devs[@]} -eq 0 ]; then \
		echo "No USB devices found."; exit 1; \
	fi; \
	echo ""; \
	i=1; for d in $${devs[@]}; do echo "  $$i) $$d"; i=$$((i+1)); done; \
	echo ""; \
	printf "Select device [1-$${#devs[@]}]: "; read n; \
	if [ "$$n" -ge 1 ] 2>/dev/null && [ "$$n" -le $${#devs[@]} ] 2>/dev/null; then \
		sel=$${devs[$$((n-1))]}; \
		echo "$$sel" > .espport; \
		echo "=> $$sel"; \
	else \
		echo "Invalid selection."; exit 1; \
	fi
