#!/bin/bash -e

# usage message
usage() {
	echo "
Change boot mode for Raspberry Pi 4
Use u-boot and extlinux.conf
Load dtb file by u-boot

Usage:
$(basename ${0}) [<kernel flavour>]
 Configure boot kernel <kernel flavour>
$(basename ${0}) --update-uboot-only
 Update u-boot files from /usr/share/u-boot/rpi_4 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 "$ubootpath" -maxdepth 1 -mindepth 1 ! -name 'config.txt' ! -name 'bcm2711-rpi-4-b.dtb' -type f | xargs cp -ft "$bootmountpoint/"
	exit 0
else
# TODO
# Нужно написать выдачу предупреждение пользователю, что все файлы
# на BOOT будут переписаны и запрос подтверждения операции, как в alt-rootfs-installer
# Restore files on BOOT from /usr/share/u-boot/rpi_4
	cp -fR "$ubootpath/"* "$bootmountpoint/"
# Overlays are not needed for u-boot
	rm -rf "$bootmountpoint/overlays"
fi

kernel_info_get $1

# Back up the file extlinux.conf before changing
cp "$extlinuxconf" "$extlinuxconf.bkp$(date +%d%m%Y%H%M%S)"

# Test labels in extlinux.conf and find last label with required flavour
change_default_label $1

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