#!/bin/bash

LOG_FILE="../uboot_build_$(date +%Y%m%d_%H%M%S).log"
BL31="bl31.elf"
TPL="rkbin/bin/rk35/rk3566_ddr_1056MHz_v1.23.bin"
UBOOT_DIR="$(pwd)/Uboot-mainline"
echo "Checking Files/directories..."

if [ ! -d "$UBOOT_DIR" ]; then
    echo "No U-BOOT source directory is found at $UBOOT_DIR. Please clone the source first"
    exit 1
fi

echo "U-BOOT source is available!"

if [ ! -f "$BL31" ]; then
	echo "BL31 not found!"
	exit 1
fi

echo "BL31 trusted firmware is available!"

if [ ! -f "$TPL" ]; then
	echo "Rockchip TPL not found!"
	exit 1
fi

echo "Rockchip TPL is available!"

echo "Checking config status..."
cd "$UBOOT_DIR" || exit 1

if [ ! -f .config ]; then
    echo "U-BOOT is not yet configured. Configuring with board default..."
    make CROSS_COMPILE=aarch64-linux-gnu- radxa-cm3-io-rk3566_defconfig
    echo "U-BOOT has been configured with the board default!"
fi


read -p "Do you want to make changes to the config? (y/n): " p1

case $p1 in
    [Yy]* )
        echo "Opening menuconfig..."
        make CROSS_COMPILE=aarch64-linux-gnu- menuconfig
        ;;
esac

echo "Compiling U-boot..."
make -j $(nproc) CROSS_COMPILE=aarch64-linux-gnu- BL31=../$BL31 ROCKCHIP_TPL=../$TPL KCFLAGS="-Wno-maybe-uninitialized" | tee -a $LOG_FILE

if [ ! $? = 0 ]; then
    echo "build failed!"
    exit 1
fi

echo "Done!"
echo "Wrapping up..."

cp u-boot.itb ../
cp idbloader.img ../
