# Makefile — generated by `l8i --emit yosys,limesdr_mini_2`.
# The ECP5 chain ([board_limesdr-01]): yosys, nextpnr-ecp5, ecppack, then the
# board's own programmer.  Regenerate rather than edit.
NAME    = top
DESIGN  = top_hciu.v
DEVICE  = 45k
PACKAGE = CSFBGA285
SPEED   = 6
FREQ    = 40

# The tools are found under OSS_PREFIX (bin/ on PATH, lib/ on the library path:
# a nextpnr-ecp5 built from source links its Boost there).
OSS_PREFIX ?=
export PATH := $(OSS_PREFIX)/bin:$(PATH)
export LD_LIBRARY_PATH := $(OSS_PREFIX)/lib:$(LD_LIBRARY_PATH)
need = @command -v $(1) >/dev/null || { echo "$(1) is not installed under $(OSS_PREFIX)"; exit 1; }

all: synth
build: synth
synth: $(NAME).bit pincheck

$(NAME).json: $(DESIGN) $(NAME).v
	$(call need,yosys)
	yosys -p 'read_verilog $(DESIGN); read_verilog $(NAME).v; synth_ecp5 -top $(NAME); write_json $@' -l $(NAME).rpt

$(NAME).config: $(NAME).json $(NAME).lpf
	$(call need,nextpnr-ecp5)
	nextpnr-ecp5 --$(DEVICE) --package $(PACKAGE) --speed $(SPEED) --freq $(FREQ) \
	  --json $(NAME).json --lpf $(NAME).lpf --textcfg $@ --log $(NAME).pnr.log

$(NAME).bit: $(NAME).config
	$(call need,ecppack)
	ecppack --bootaddr 0 --compress $< --bit $@

# THE FAR CHIPS' PIN TIMING ([board-76], [board_limesdr-18]): nextpnr-ecp5 checks none, so
# the margins are ESTIMATED from the pad cells (top.pins: the board's numbers and the
# part's pad-cell model) -- not a tool-checked number; `--emit diamond` is the reference.
# A negative margin fails the build; `make PINCHECK=warn` reports and goes on.
PINCHECK ?= fail
pincheck: $(NAME).config $(NAME).pins pincheck.py
	$(call need,python3)
	@python3 pincheck.py $(if $(filter warn,$(PINCHECK)),--warn) -o $(NAME).pin.rpt $(NAME).pins $(NAME).json $(NAME).pnr.log

# How this board is loaded is the BOARD's property ([board_icestick-02]): the SRAM
# over its cable; prog-flash writes the configuration flash it boots from.
prog: $(NAME).bit
	$(call need,openFPGALoader)
	openFPGALoader -c ft2232 $<

prog-flash: $(NAME).bit
	$(call need,openFPGALoader)
	openFPGALoader -c ft2232 -f $<

toolchain-check:
	@for t in yosys nextpnr-ecp5 ecppack openFPGALoader; do printf '%-16s %s\n' $$t "$$(command -v $$t || echo 'not found')"; done

clean:
	rm -f $(NAME).json $(NAME).config $(NAME).bit $(NAME).rpt $(NAME).pnr.log $(NAME).pin.rpt

.PHONY: all synth build prog prog-flash clean toolchain-check pincheck
