# Build uspiflash-linux: a header generated by uspiflash, then the tool,
# statically linked by default (`make LDFLAGS=` for dynamic). uspiflash runs
# through uv by default; `make USPIFLASH=uspiflash` uses an installed one.
UV        ?= uv
USPIFLASH ?= $(UV) run uspiflash
CC        ?= cc
LDFLAGS   ?= -static
CFLAGS    ?= -Os
# Every chip type and every extra that changes the output, as `spiflash id`.
GENERATE = --level full --type nor --type nand --with sfdp --with sfdp_dumps \
           --with datasheet --with datasheets --with records --with provenance
# Lazy: only the targets that need it run uspiflash (`make clean` does not).
VERSION = $(shell $(USPIFLASH) --version)
override CFLAGS += -std=c99 -Wall -Wextra -Wpedantic -Wundef -Wshadow -Werror -D_DEFAULT_SOURCE

build/uspiflash-linux: uspiflash-linux.c build/uspiflash.h
	$(CC) $(CFLAGS) "-DUSPIFLASH_LINUX_VERSION=\"$$(cat build/version)\"" -Ibuild $(LDFLAGS) \
	    -o $@ $<

# The header is remade whenever `uspiflash --version` (which names spiflash's
# version too) changes: build/version is rewritten only then.
build/uspiflash.h: build/version
	$(USPIFLASH) generate -o $@ $(GENERATE)

build/version: FORCE
	@mkdir -p build
	@v='$(VERSION)'; test -n "$$v" || { echo '$(USPIFLASH) --version failed' >&2; exit 1; }; \
	printf '%s\n' "$$v" | cmp -s - $@ || printf '%s\n' "$$v" > $@

clean:
	rm -rf build

FORCE:

.PHONY: clean FORCE
