MAKEFLAGS    += -R -r

ARDUINO_CLI   = arduino-cli
ZIP	      = zip
PERL	      = perl

SKETCH	      = max80
TARGET	      = output/$(SKETCH).ino.bin
fromcommon   := $(patsubst ../common/%,$(SKETCH)/src/common/%,$(wildcard ../common/*.[ch]))
GENFILES      = www.zip
WWW	      = www
PORT	     ?= /dev/ttyACM0

build_defines = -DBOARD_HAS_PSRAM -I. -Isrc/common

BOARD	      = esp32:esp32:esp32s2usb
ARDUINO_OPTS  = -b $(BOARD) \
		--warnings all \
		--build-path       ../build \
		--output-dir       ../output \
		--build-cache-path ../cache \
		--build-property 'build.flash_size=4MB' \
		--build-property 'build.defines=$(build_defines)' \
		--build-property 'build.cdc_on_boot=1' \
		--build-property 'build.msc_on_boot=0' \
		--build-property 'build.dfu_on_boot=0' \
		--build-property 'build.partitions=min_spiffs'

all: $(TARGET)

properties:
	cd $(SKETCH) && \
		$(ARDUINO_CLI) compile --show-properties $(ARDUINO_OPTS)

$(TARGET): $(shell find $(SKETCH) -type f) $(GENFILES) $(fromcommon)
	mkdir -p build output cache
	cd $(SKETCH) && \
		$(ARDUINO_CLI) compile $(ARDUINO_OPTS)

common_dir:
	mkdir -p $(SKETCH)/src/common

$(SKETCH)/src/common/%: ../common/% | common_dir
	cp -f $< $@

.PHONY: zip
zip: zipexclude
	mkdir -p zip
	if ! cmp -q ../version.mk www/version 2>/dev/null; then \
		cp -f ../version.mk www/version; \
	fi
	cd www && \
		TZ=GMT0 \
		$(ZIP) -9DrpX -UN=UTF8 -FS ../zip/www.zip . -x@../zipexclude

# Ugly hack but needed to avoid unnecessary rebuilds
www.zip: zip
	if [ ! -f $@ ] || [ zip/$@ -nt $@ ]; then \
		cp -f zip/$@ $@; \
		rm -f build/sketch/www.c build/sketch/www.c.*; \
	fi

upload: $(TARGET)
	$(ARDUINO_CLI) upload -i $(TARGET) -p $(PORT) -b $(BOARD) $(SKETCH)

clean:
	rm -rf build cache zip $(GENFILES) $(SKETCH)/src/common

spotless: clean
	rm -rf output
