#!/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
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_arm64/u-boot.bin ] && [ "$ARCH" = "aarch64" ]; then
		cp -rp /usr/share/uboot/rpi_arm64/u-boot.bin /boot/efi/rpi-u-boot.bin
fi

# copy firmware files if running on iot
if [ "$(grep "VARIANT=\"IoT Edition\"" /etc/os-release)" != "" ]; then
        echo "== Detected IoT Edition, copying Raspberry Pi firmware files."
        if [ -d /usr/lib/ostree-boot/efi/ ]; then
                cp -rfp /usr/lib/ostree-boot/efi/*.{bin,dat,elf} /boot/efi/
                echo "== Copying new config.txt to config.txt.rpmnew"
                cp -rfp /usr/lib/ostree-boot/efi/config.txt /boot/efi/config.txt.rpmnew
        fi
fi
# reboot after writing
if [ "$REBOOT" = "1" ]; then
	echo
        echo "= Complete, rebooting.."
        reboot
else
	echo
        echo "= Complete!"
fi
