#!/usr/bin/sh
usage() {
    echo "
Usage: $(basename ${0}) <options>
	--reboot
"
}

# check the args
while [ $# -gt 0 ]; do
        case $1 in
                --debug)
                        set -x
                        ;;
                -h|--help)
                        usage
                        exit 0
                        ;;
		--reboot)
			REBOOT=1
			;;
	esac
	shift
done
# ensure sudo user
if [ "$(whoami)" != "root" ]; then
	echo "Error: This script requires 'sudo' privileges in order to write to disk & mount media."
	exit 1
fi

if [ "$(uname -m)" == "aarch64" ] ; then
	ARCH="aarch64"
	DESTDIR="/boot/efi"
	UBOOT=$(rpm -q uboot-images-armv8)
	UBOOTPKG=uboot-images-armv8
elif [ "$(uname -m)" == "armv7l" ] ; then
	ARCH="armv7l"
	DESTDIR="/boot/efi"
	UBOOT=$(rpm -q uboot-images-armv7)
	UBOOTPKG=uboot-images-armv7
fi

echo
echo "= This will update U-Boot to:"

if [ "$UBOOT" = "package ${UBOOTPKG} is not installed" ]; then
	echo
	echo "$UBOOT"
	read -p "Would you like to install ${UBOOTPKG} (yes or no)? " INSTALL_UBOOT
	if [ "$(echo ${INSTALL_UBOOT} | tr [:lower:] [:upper:])" = "YES" ]; then
		dnf install -y ${UBOOTPKG}
		UBOOT=$(rpm -q ${UBOOTPKG})
	fi
fi
echo
echo "= Version - $UBOOT"

if [ -f /usr/share/uboot/rpi_4/u-boot.bin ] && [ "$ARCH" = "aarch64" ]; then
		cp -rp /usr/share/uboot/rpi_4/u-boot.bin /boot/efi/rpi4-u-boot.bin
fi
if [ -f /usr/share/uboot/rpi_3/u-boot.bin ] && [ "$ARCH" = "aarch64" ]; then
		cp -rp /usr/share/uboot/rpi_3/u-boot.bin /boot/efi/rpi3-u-boot.bin
fi
if [ -f /usr/share/uboot/rpi_2/u-boot.bin ] && [ "$ARCH" = "armv7l" ]; then
		cp -rp /usr/share/uboot/rpi_2/u-boot.bin /boot/efi/rpi2-u-boot.bin
fi
if [ -f /usr/share/uboot/rpi_3_32b/u-boot.bin ] && [ "$ARCH" = "armv7l" ]; then
		cp -rp /usr/share/uboot/rpi_3_32b/u-boot.bin /boot/efi/rpi3-u-boot.bin
fi
# reboot after writing
if [ "REBOOT" = "1" ]; then
	echo
        echo "= Complete, rebooting.."
        reboot
else
	echo
        echo "= Complete!"
fi
