# project file name (use for schematic and board layout)
NAME ?= hdmi_firewall
# path to qeda
QEDA := qeda

# read project version
VERSION := $(shell cat version)
# current date for stamping output
DATE = $(shell date +%Y-%m-%d)
# revision based on number of changes on schematic or board layout and current git commit
REVISION := $(shell git log --pretty=oneline "${NAME}.kicad_sch" "${NAME}.kicad_pcb" | wc -l)

# generate file with version information
VERSIONED_EXT = kicad_sch kicad_pcb kicad_pro json
define version_rule
%.versioned.$1: %.$1
	cp $$< $$@
	sed --in-place 's/\$$$$version\$$$$/${VERSION}/g' $$@
	sed --in-place 's/\$$$$date\$$$$/${DATE}/g' $$@
	sed --in-place 's/\$$$$revision\$$$$/${REVISION}/g' $$@
endef
$(foreach EXT,$(VERSIONED_EXT),$(eval $(call version_rule,$(EXT))))

all: print fabrication

print: ${NAME}.sch.pdf ${NAME}.brd-top.png ${NAME}.brd-bot.png ${NAME}.bom.csv

# generate fabrication files (gerbers/drill/BoM/PnP)
FABRICATION_DIR := fabrication
fabrication: ${NAME}.versioned.kicad_sch ${NAME}.versioned.kicad_pcb
	kikit fab jlcpcb --drc --assembly --schematic $^ ${FABRICATION_DIR}

# generate symbols and footprints from parts
lib:
	$(QEDA) generate qeda

# generate printable version (PDF) of schematic
%.sch.pdf: %.versioned.kicad_sch %.versioned.kicad_pro
	eeschema_do export $< .
	mv $*.versioned.pdf $@

# generate render from layout (top side)
%.brd-top.png: %.versioned.kicad_pcb
	pcbdraw --silent $< --dpi 600 $@

# generate render from layout (bottom side)
%.brd-bot.png: %.versioned.kicad_pcb
	pcbdraw --silent $< --dpi 600 --back $@

# export Bill of Material (as CSV)
%.bom.csv: %.versioned.kicad_sch %.versioned.kicad_pro
	eeschema_do bom_xml $< .
	kibom $*.versioned.xml $@

# generate panel
PANEL_DIR := panel
panel: panel.kicad_pcb
panel.kicad_pcb: ${NAME}.versioned.kicad_pcb ${NAME}.versioned.kicad_pro ${NAME}.versioned.kicad_sch ${NAME}.versioned.json
	kikit panelize -p ${NAME}.versioned.json ${NAME}.versioned.kicad_pcb $@
	sed --in-place 's/\"missing_courtyard\": \"warning\"/\"missing_courtyard\": \"ignore\"/g' $(patsubst %.kicad_pcb,%.kicad_pro,$@) # the mouse bites don't have a courtyard
	kikit fab jlcpcb --drc --assembly --missingError --schematic ${NAME}.versioned.kicad_sch $@ ${PANEL_DIR}
	pcbdraw --silent $@ --dpi 600 panel.brd-top.png
	pcbdraw --silent $@ --dpi 600 --back panel.brd-bot.png

clean:
	rm -f $(foreach EXT,$(VERSIONED_EXT),${NAME}.versioned.$(EXT))
	rm -f ${NAME}.sch.pdf ${NAME}.brd-top.png ${NAME}.brd-bot.png ${NAME}.versioned.xml ${NAME}.bom.csv
	rm -f ${NAME}.versioned.kicad_prl ${NAME}.versioned.kicad_pro-bak ${NAME}.versioned.xml ${NAME}.versioned.csv
	rm -rf ${FABRICATION_DIR}
	rm -f panel.kicad_pcb panel.kicad_pro 
	rm -rf ${PANEL_DIR}
