MAKEFLAGS += -R -r

PROJECT   := max80
SUBDIRS   := common esp32 tools rv32 fpga
REVISIONS := v1 v2 bypass

GIT_DIR   ?= .git
TEMP      ?= /tmp

MAX80_IP  ?= max80.local

CURL	   = curl
PERL	   = perl
PYTHON     = python
ESPTOOL   ?= esptool
export ESPTOOL

all clean spotless :
	$(MAKE) local.$@ $(SUBDIRS) goal=$@

prefpga:
	$(MAKE) local.all $(filter-out fpga,$(SUBDIRS)) goal=all

$(REVISIONS): prefpga
	$(MAKE) -C fpga $@

.PHONY: $(SUBDIRS)
$(SUBDIRS):
	$(MAKE) -C $@ $(goal)

.PHONY: version.mk
version.mk:
	if git log -n 1 --date=iso --pretty="format:\
PROJECT=$(PROJECT)%n\
COMMIT_VERSION=%(describe:abbrev=6)%n\
COMMIT_ID=%H%nCOMMIT_MAGIC=%h%n\
COMMIT_DATE=%ci%n\
COMMIT_TIME=%ct%n\
COMMIT_AUTHOR=%an <%ae>%n\
" > '$@.tmp' 2>/dev/null && \
	! cmp -s '$@' '$@.tmp' 2>/dev/null; then \
	mv -f '$@.tmp' '$@'; else rm -f '$@.tmp'; fi

version.%: version.mk version.%.sed
	sed -f $@.sed $< > $@

.PHONY: version
version: version.mk version.h version.vh

$(SUBDIRS): version.mk

esp32: version.h | common

rv32: version.h | common tools

fpga: version.vh | rv32 esp32

local.all:

local.clean:
	rm -f *~ ./\#* \# *.bak *.tmp stamp_*.bin

local.spotless: local.clean
	rm -f version.h version.vh
	if [ -d .git ]; then rm -f version.mk; fi

# Obsolete target, need version
program flash:
	@echo 'Please specify one of: $(foreach rev,$(REVISIONS),$@-$(rev))' 1>&2
	@false

# FPGA-specific targets
program-% flash-%: prefpga
	$(MAKE) -C fpga $@

# ESP update by USB or serial port using esptool directly
upload-esp:
	$(MAKE) -C esp32 upload

ip = $(MAX80_IP)

# Generic upload for newer firmware (as opposed to specifying a version)
upload: upload-$(PROJECT)

ifeq ($(PORT),)
# --- Upload via HTTP ---

upload-%:
	$(CURL) -v --data-binary @fpga/output/$*.fw 'http://$(ip)/sys/fwupdate'

# setver is not supported via HTTP
setver-%:
	@echo 'make $@ requires PORT= to be specified'
	@exit 1

else
# --- Upload via serial port/USB

FLASHMAX = $(PERL) ./tools/flashmax.pl --port '$(PORT)' $(FLASHOPT)

# Version-specific uploads for older firmware
upload-%:
	$(FLASHMAX) fpga/output/$*.fw

# Write board ID/revision to flash
setver-%:
	$(FLASHMAX) --setver 'MAX80 v$*'

endif
