#!/bin/bash -e

# Clean everything except prebuilt ARM toolchain
if [ "$1" == "clean" ]; then
    rm -rf embeddedsw GenZ output.bif ps7_init_sdboot BOOT.BIN
    make clean
    exit 0
fi

test -d GenZ || git clone https://github.com/regymm/GenZ
PYTHONPATH=GenZ python3 ./sdboot.py

# Prepare BSP folder for PYNQ-Z1
test -d embeddedsw || git clone https://github.com/regymm/embeddedsw --depth=1
cp -a embeddedsw/lib/sw_apps/zynq_fsbl/misc/{muzy4,pynqz1}
# Copy the BSP files generated by GenZ
cp ps7_init_sdboot/* embeddedsw/lib/sw_apps/zynq_fsbl/misc/pynqz1

# apt install gcc-arm-none-eabi version will not work!
# wget https://developer.arm.com/-/media/Files/downloads/gnu/14.2.rel1/binrel/arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi.tar.xz
# tar xf arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi.tar.xz
test -d arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi/bin || (wget https://developer.arm.com/-/media/Files/downloads/gnu/14.2.rel1/binrel/arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi.tar.xz && tar xf arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi.tar.xz)
export PATH=`pwd`/arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi/bin:$PATH
make BOARD=pynqz1 "CFLAGS=-DAXI_TEST" -C embeddedsw/lib/sw_apps/hello_world/src
make BOARD=pynqz1 "CFLAGS=-DFSBL_DEBUG_INFO -DNODDR" -C embeddedsw/lib/sw_apps/zynq_fsbl/src

# Prepare BOOT.BIN for SD Boot
# need: apt install libelf-dev
test -d zynq-mkbootimage || git clone https://github.com/antmicro/zynq-mkbootimage --depth=1
make -C zynq-mkbootimage

# Prepare bif
cat > output.bif << EOF
the_ROM_image:
{
	[bootloader]embeddedsw/lib/sw_apps/zynq_fsbl/src/fsbl.elf
	ps7_axi_blinky.bit
	embeddedsw/lib/sw_apps/hello_world/src/hello-world.elf
}
EOF

# Generate bitstream with openXC7
NEXTPNR_XILINX_DIR=/nextpnr-xilinx/xilinx make

# Generate BOOT.BIN
./zynq-mkbootimage/mkbootimage output.bif BOOT.BIN

