#!/bin/bash -e

# usage message
usage() {
	echo "
Change boot mode for Raspberry Pi 4
Use u-boot and extlinux.conf.
Do not load dtb file by u-boot.
Load dtb file by firmware and transfer
the modified dtb in memory to the kernel through u-boot.

Usage:
$(basename ${0}) [<kernel flavour>]
 Configure boot kernel <kernel flavour>
$(basename ${0}) --help
 Print this message
"
}

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

. /usr/sbin/rpi4-boot-common

kernel_info_get $1
dtbdirname_get

# 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"

# TODO
# Пусть u-boot не умеет пока подгружать оверлеи к dtb.
# Но firmware это умеет, а в этом режиме u-boot передаёт ядру dtb, загруженный firmware.
# Если этот режим работы будет востребован (что сомнительно) то нужно сделать копирование
# оверлеев на BOOT и пропись их в config.txt.
# Test required dtb file on BOOT
if [ ! -d "$bootmountpoint/$dtbdirname" ]
then
# No required dtb file on BOOT. Copy
	mkdir -p "$bootmountpoint/$dtbdirname/"
	cp "$dtbpath/$dtbdirname/$rpi4dtb" "$bootmountpoint/$dtbdirname/"
fi

#    Firmware RasPi4 load bcm2711-rpi-4-b.dtb, modifies and passes
#    the modified version to the kernel.
#    https://www.raspberrypi.org/documentation/configuration/device-tree.md
#    If u-boot is used to load the kernel, then you need to transfer
#    the modified dtb in memory to the kernel through u-boot.
#    Without setting the "device_tree_address" parameter, u-boot displays
#    "ERROR: Did not find a cmdline Flattened Device Tree"
#    message and the system does not boot.
# Test device_tree=, device_tree_address= in config.txt
dtbconfigtxt=$(grep -v '^#' "$configpath" | grep 'device_tree=' | sed 's/^device_tree=//')
dtbaddrconfigtxt=$(grep -v '^#' "$configpath" | grep 'device_tree_address=' | sed 's/^device_tree_address=//')
if [ "$dtbconfigtxt" != "$dtbdirname/$rpi4dtb" -o "$dtbaddrconfigtxt" != "$dtbaddr" ]
then
# No required device_tree= or device_tree_address= in config.txt. Write down
	cp "$configpath" "$bootmountpoint/config.bkp$(date +%d%m%Y%H%M%S)"
	sed -i 's/^device_tree=/# device_tree=/ ; s/^device_tree_address=/# device_tree_address=/' "$configpath"
	echo "device_tree_address=$dtbaddr" >> "$configpath"
	echo "device_tree=$dtbdirname/$rpi4dtb" >> "$configpath"
fi

# 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

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