BASE_DIR           := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
LIBRARY_DIR        := $(BASE_DIR)/lib

ifndef MONITOR_PORT
  ifneq (,$(wildcard /dev/ttyUSB0))
    MONITOR_PORT = /dev/ttyUSB0
  else ifneq (,$(wildcard /dev/ttyACM0))
    MONITOR_PORT = /dev/ttyACM0
  else
    MONITOR_PORT = unknown
  endif
endif

ESPTOOL            := $(BASE_DIR)/hardware/esp8266/tools/esptool/esptool
ESPOTA             := $(BASE_DIR)/hardware/esp8266/tools/espota.py
TARGET_DIR         := $(BASE_DIR)/$(subst :,.,build/$(FQBN))
BIN_DIR            := $(BASE_DIR)/bin
SRC                := $(wildcard $(SKETCH_DIR)/*.ino)
HDRS               := $(wildcard $(SKETCH_DIR)/*.h)
BIN                := $(notdir $(SRC)).bin

$(info FQBN         is [${FQBN}])
$(info ESP_IP       is [${ESP_IP}])
$(info OTA_SERVER   is [${OTA_SERVER}])
$(info OTA_PASSWD   is [${OTA_PASSWD}])
$(info MONITOR_PORT is [${MONITOR_PORT}])
$(info TARGET_DIR   is [${TARGET_DIR}])
$(info BIN_DIR      is [${BIN_DIR}])
$(info SRC          is [${SRC}])
$(info HDRS         is [${HDRS}])
$(info BIN          is [${BIN}])
$(info SERIAL_DEV   is [${SERIAL_DEV}])

all: $(BIN_DIR)/$(BIN) upload

compile: $(BIN_DIR)/$(BIN)

upload: $(BIN_DIR)/$(BIN)
	$(ESPTOOL) -v -cd nodemcu -b 115200 -p $(MONITOR_PORT) -ca 0x00000 -cf $(TARGET_DIR)/$(SKETCH).bin

ota: $(BIN_DIR)/$(BIN)
	$(ESPOTA) -d -r -i $(ESP_IP) -I $(OTA_SERVER) -p 8266 -P 8266 -a $(OTA_PASSWD) -f $(TARGET_DIR)/$(SKETCH).bin

clean:
	rm -rf $(TARGET_DIR)

monitor:
	screen $(MONITOR_PORT) 115200

new-library:
	$(eval NEW_LIB = $(LIBRARY_DIR)/$(LIB))
	mkdir -p $(NEW_LIB)
	$(eval UC = $(shell echo '$(LIB)' | tr '[:lower:]' '[:upper:]'))

	@ echo "#ifndef $(UC)_h" >  $(NEW_LIB)/$(LIB).h
	@ echo "#define $(UC)_h" >> $(NEW_LIB)/$(LIB).h
	@ echo ""                >> $(NEW_LIB)/$(LIB).h
	@ echo "#endif"          >> $(NEW_LIB)/$(LIB).h

.PHONY: all compile test library upload ota clean monitor

$(TARGET_DIR)/$(BIN): $(SRC) $(HDRS)
	@ echo $(FQBN)
	@ mkdir -p $(TARGET_DIR)

	arduino-cli compile -logger=machine \
	--fqbn=$(FQBN) \
	--library "$(subst $(space),$(sep),$(strip $(sort $(dir $(wildcard $(LIBRARY_DIR)/*/)))))" \
	--build-path "$(TARGET_DIR)" \
	--warnings=none \
	--verbose \
	"$(SKETCH_DIR)/$(SKETCH)"

$(BIN_DIR)/$(BIN): $(TARGET_DIR)/$(BIN)
	@ echo "$(BIN) $(BIN_DIR)/"
	@ cp $(TARGET_DIR)/$(BIN) $(BIN_DIR)/
