GIT_VERS = $(shell git rev-parse --short HEAD)
SUBDIRS = $(patsubst %/,%,$(shell ls -d */))
$(info $(SUBDIRS))

HW_TARGETS := tef1001_R1 tef1001_R2 xpressk7_160 xpressk7_325 kc705 nereid
STATUS_LOG := build_status.log

# The summary is printed by the recipe of "all", which only runs after every
# configuration has finished (with make -j a sibling prerequisite "report" would
# run at once and print an empty table).
all: $(SUBDIRS)
	@$(MAKE) --no-print-directory report

vers:
	./make_version.sh
	@printf "%-30s %-14s %-16s %8s\n" "CONFIG" "HW" "STATUS" "WNS(ns)" > $(STATUS_LOG)

$(SUBDIRS): vers
	@for hw in $(HW_TARGETS); do bash ./build_status.sh $@ $$hw $(STATUS_LOG); done

# Rows are appended by parallel builds in the order they finish, so sort them.
report:
	@echo "==== Build status summary ===="
	@if [ -f $(STATUS_LOG) ]; then \
	    head -1 $(STATUS_LOG); tail -n +2 $(STATUS_LOG) | sort; \
	    echo "----"; tail -n +2 $(STATUS_LOG) | awk '{c[$$3]++; n++} END {printf "%d builds:", n; for (k in c) printf " %d %s", c[k], k; printf "\n"}'; \
	else echo "No build status yet, run 'make' first."; fi

# hdlmake 3.3 cannot parse the Vivado 2024.1 IP files (*.xci are JSON), 4.0 or newer is needed.
HDLMAKE_MIN_MAJOR := 4
hdlmake-check:
	@v=$$(hdlmake --version 2>&1 | sed -n 's/^hdlmake \([0-9][0-9]*\)\..*/\1/p'); \
	if [ -z "$$v" ] || [ "$$v" -lt $(HDLMAKE_MIN_MAJOR) ]; then \
	    echo "ERROR: hdlmake $(HDLMAKE_MIN_MAJOR).0 or newer is required, found: $$(hdlmake --version 2>&1 | head -1)"; \
	    echo "       see 'How to build' in README.md (a copy in ~/.local can shadow the system one)"; exit 1; fi

# Each target in its own subshell: one failure is reported by name and does not
# leave the loop in the wrong directory.
hdl: vers hdlmake-check
	@fail=0; for d in $(SUBDIRS); do for hw in $(HW_TARGETS); do \
	    (cd $$d/$$hw && hdlmake) || { echo "FAILED: $$d/$$hw"; fail=1; }; \
	done; done; exit $$fail

clean:
	for d in $(SUBDIRS); do for hw in $(HW_TARGETS); do make -C $$d/$$hw clean; done; done
	rm -f $(STATUS_LOG) */*/build_console.log

deploy:
	ssh lxplus.cern.ch "mkdir -p /eos/user/t/theim/www/yarr/firmware/$(GIT_VERS) &&\
		rm -f /eos/user/t/theim/www/yarr/firmware/latest &&\
		ln -s /eos/user/t/theim/www/yarr/firmware/$(GIT_VERS) /eos/user/t/theim/www/yarr/firmware/latest"
	rsync -av --include '*/' --include '*_*_*.bit' --exclude '*' --prune-empty-dirs ./ lxplus.cern.ch:/eos/user/t/theim/www/yarr/firmware/$(GIT_VERS)
	rsync -av ../../script/flash.sh lxplus.cern.ch:/eos/user/t/theim/www/yarr/firmware/flash.sh

.PHONY: all clean hdl hdlmake-check vers report $(SUBDIRS)
