#! /bin/bash

SW_DIR=../../sw    #relative to sw/boot dir
OUTPUT_DIR=./boot/output #relative to sw sir
SYN_DIR=../hdl/syn #relative to sw dir

mkdir -p ${SW_DIR}/$OUTPUT_DIR

board=zynq_spec7
defconfig=${board}_defconfig
USE_UART=0
cd $SW_DIR  

#Default bitfile's are the most recent bitfiles in the syn dir.
TANDEM_GATEWARE=../../$SYN_DIR/$(ls -t $SYN_DIR | grep .bit | grep tandem | head -n 1)
REFERENCE_GATEWARE=../../$SYN_DIR/$(ls -t $SYN_DIR| grep .bit | grep ref | head -n 1)
OFFSET=0x1000000

while getopts t:r:o:u:h flag
do
    case "${flag}" in
        t) TANDEM_GATEWARE=${OPTARG};;
        r) REFERENCE_GATEWARE=${OPTARG};;
        o) OFFSET=${OPTARG};;
        u) USE_UART=${OPTARG};;
        h) echo Usage: $0 -t {Tandem_bitfile} -r {Reference_bitfile} -o {Memory_Offset};
           echo -t {Tandem_bitfile} location of the bitfile used in tandem PCIe boot. Default is the most recent bitfile in spec7/hdl/syn/ containing the word "tandem".;
           echo -r {Reference_bitfile} location of the bitfile used in the reference design. Default is the most recent bitfile in spec7/hdl/syn/ containing the word "ref".;
           echo -o {Memory_Offset} the DDR3 Memory offset where the reference design is loaded into. Default is 0x1000000.;
           echo -u {uboot uart channel} The uart channel number where Cout and Cin is directed. Default is 0.; 
           echo -h Prints this help message.;
           exit 1;;
    esac
done

for dir in $(ls)
do

    if [ "$dir" == "fsbl" ];then
        make -C  $dir
        cp $dir/zynq_fsbl.elf $OUTPUT_DIR
    fi

    if [ "$dir" == "spec7-ps-sw" ];then
        if [ "$USE_UART" == "1" ]; then
          sed -i "s/uart0;/uart1;/" $dir/uboot/arch/arm/dts/zynq-spec7.dts
          sed -i "s/CONFIG_DEBUG_UART_BASE=0xe0000000/CONFIG_DEBUG_UART_BASE=0xe0001000/" $dir/uboot/configs/zynq_spec7_defconfig
          sed -i "s/CONFIG_ENV_OFFSET=0xFE0000/CONFIG_ENV_OFFSET=0xFC0000/" $dir/uboot/configs/zynq_spec7_defconfig
        else
          sed -i "s/uart1;/uart0;/" $dir/uboot/arch/arm/dts/zynq-spec7.dts
          sed -i "s/CONFIG_DEBUG_UART_BASE=0xe0001000/CONFIG_DEBUG_UART_BASE=0xe0000000/" $dir/uboot/configs/zynq_spec7_defconfig
          sed -i "s/CONFIG_ENV_OFFSET=0xFC0000/CONFIG_ENV_OFFSET=0xFE0000/" $dir/uboot/configs/zynq_spec7_defconfig
        fi
        export CROSS_COMPILE=arm-linux-gnueabihf-
        export ARCH=arm
        make -C $dir/uboot $defconfig
        make -C $dir/uboot
        cp $dir/uboot/u-boot.elf $OUTPUT_DIR
    fi

done

cd $OUTPUT_DIR

rm $(ls|grep .bif)

echo "the_ROM_image:" >> spec7.bif
echo "{" >> spec7.bif
echo "[bootloader] zynq_fsbl.elf" >> spec7.bif
echo "$TANDEM_GATEWARE" >> spec7.bif
echo "u-boot.elf" >> spec7.bif
if [ "$REFRENCE_GATEWARE" == "" ]; then
    echo "[offset = $OFFSET] $REFERENCE_GATEWARE" >> spec7.bif 
fi
echo "}" >> spec7.bif

bootgen -image spec7.bif -arch zynq -o BOOT.bin -w
