#-------------------------------------------------------------------------------
#
# Makefile
#
# generate CDI2 Device Core bitstream (vivado), firmware (vitis), and BOOT.BIN
#
# (c)2023 AIT Austrian Institute of Technology
#-------------------------------------------------------------------------------

# allow override on command line or environment
VIVADO_DIR ?= /opt/Xilinx/Vivado/2022.2
VITIS_DIR  ?= /opt/Xilinx/Vitis/2022.2

# set tool paths
XSCT      = $(VITIS_DIR)/bin/xsct
BOOTGEN   = $(VITIS_DIR)/bin/bootgen
VIVADO    = $(VIVADO_DIR)/bin/vivado
UPDATEMEM = $(VIVADO_DIR)/bin/updatemem

# define some short handles to deeply nested intermediate artefacts
FPGA_PRJ = Mars_ZX2_ST3/Mars_ZX2_ST3.xpr
FPGA_BIT = Mars_ZX2_ST3/Mars_ZX2_ST3.runs/impl_1/Mars_ZX2_ST3.bit
FPGA_MMI = Mars_ZX2_ST3/Mars_ZX2_ST3.runs/impl_1/Mars_ZX2_ST3.mmi
FPGA_ELF = Workspace.build/CDI2_Device/Release/CDI2_Device.elf

# get version from git repo tag, fall back to 1.0 if this does not work
GIT_VERSION != git describe --tags --long --dirty --always

ifeq ($(strip $(GIT_VERSION)),)
  GIT_VERSION = "1.0"
endif

# use GIT version for SW_VERSION, but allow override on command line
SW_VERSION ?= $(GIT_VERSION)

.PHONY: all clean bitstream firmware boot

all: bitstream firmware boot

# clean backup files and log directory
clean::
	rm -f *~ logs/*

#---- build FPGA design with vivado ----

# (re)create CDI2 project with nucleus script
$(FPGA_PRJ): scripts/recreate_Mars_ZX2_ST3.tcl
	$(VIVADO) -nojournal -log logs/recreate.log -mode batch -source scripts/recreate_Mars_ZX2_ST3.tcl

$(FPGA_BIT): $(FPGA_PRJ)
	$(VIVADO) -nojournal -log logs/buildBIT.log -mode batch -source scripts/buildBIT.tcl $(FPGA_PRJ)

$(FPGA_MMI): $(FPGA_BIT)

bitstream : $(FPGA_BIT)

clean::
	rm -rf Mars_ZX2_ST3 Mars_ZX2_ST3.xsa

#---- build FW with vitis ----

firmware: Workspace.build/CDI2_Device/Release/CDI2_Device.elf

# Russian variant of an out-of-tree build
Workspace.build: Workspace.src
	cp -a Workspace.src Workspace.build
	echo "#define SW_VERSION \"$(SW_VERSION)\"" > Workspace.build/CDI2_Device/include/cdi2_sw_version.h

$(FPGA_ELF): Workspace.build
	$(XSCT) scripts/buildELF.tcl 2>&1 | tee logs/buildELF.log

clean::
	rm -rf Workspace.build

#---- build BOOT.BIN ----

boot: boot/BOOT.BIN

boot/Mars_ZX2_ST3.bit: $(FPGA_BIT) $(FPGA_MMI) $(FPGA_ELF)
	cd logs; $(UPDATEMEM) --force --meminfo ../$(FPGA_MMI) --data ../$(FPGA_ELF) --bit ../$(FPGA_BIT) -proc cdi2Device/CDI2_Device_i/SoftCore --out ../boot/Mars_ZX2_ST3.bit

boot/BOOT.BIN: boot/Mars_ZX2_ST3.bit boot/bootgen.bif
	cd logs; $(BOOTGEN) -log trace -w on -arch zynq -image ../boot/bootgen.bif -o ../boot/BOOT.BIN

clean::
	rm -f boot/Mars_ZX2_ST3.bit boot/BOOT.BIN

