#!/bin/bash -e

# usage message
usage() {
	echo "
Change boot mode or update firmware and u-boot for Raspberry Pi 4

On armv7l (armh) use u-boot and extlinux.conf to boot
Load dtb file by u-boot

On aarch64 use u-boot and GRUB-EFI
This mode is intended for a 64-bit system
in which the FAT partition is mounted in /boot/efi

Usage:
$(basename ${0})
 Change boot mode
$(basename ${0}) --update-uboot-only
 Update firmware and u-boot files only
$(basename ${0}) --help
 Print this message
"
}

if [ "$1" == "--help" ]
then
	usage
	exit 0
fi

. /usr/sbin/rpi4-boot-common

if [ "$1" = "--update-uboot-only" ]; then
	find "$ubootpath3" -maxdepth 1 -mindepth 1 ! -name "$ubootfile" ! -name 'config.txt' ! -name 'bcm2710-rpi-3*.dtb' -type f | xargs cp -ft "$bootmountpoint/"
	cp -f "$ubootpath3/$ubootfile" "$bootmountpoint/$ubootfile3"
	find "$ubootpath" -maxdepth 1 -mindepth 1 ! -name "$ubootfile" ! -name 'config.txt' ! -name 'bcm2711-rpi-4-b.dtb' -type f | xargs cp -ft "$bootmountpoint/"
	cp -f "$ubootpath/$ubootfile" "$bootmountpoint/$ubootfile4"
	exit 0
fi

if [ "$systemarch" == "aarch64" -a ! -f "$bootmountpoint/EFI/BOOT/BOOTAA64.EFI" ]; then
	echo "Warning: The boot mode using extlinux for aarch64 is
experimental and the system may not boot.
In this case, connect the memory card to another computer
and rename config.bkp to config.txt in FAT partition."
fi

set_boot_uboot

# Back up the file extlinux.conf before changing
cp -f "$extlinuxconf" "$extlinuxconf.bkp"

# Delete all # in fdtdir strings for loading dtb file by u-boot
sed -i 's/^#\s\+fdtdir/\tfdtdir/' "$extlinuxconf"
