#!/bin/bash -e

# usage message
usage() {
	echo "
Change boot mode for Raspberry Pi 4
Do not use u-boot and extlinux.conf
Use parameters
  kernel=
  device_tree=
  initramfs
  cmdline=
from config.txt
https://www.raspberrypi.org/documentation/configuration/config-txt/boot.md

Usage:
$(basename ${0}) [<kernel flavour>]
 Configure boot kernel <kernel flavour>
$(basename ${0}) --default
 Configure boot kernel by default symlinks
  /boot/vmlinuz
  /boot/initrd.img
  /boot/dtb
$(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

# Rewrite dtb on BOOT
cd "$dtbpath/$dtbdirname"
cp -f $rpidtb "$bootmountpoint/"
# Change overlays on BOOT
rm -rf "$bootmountpoint/overlays"
cp -rf "overlays" "$bootmountpoint/"
cd - >/dev/null

# Rewrite vmlinuz on BOOT
if [ -f "/boot/$kernelfilename" ]; then
	cp -f "/boot/$kernelfilename" "$bootmountpoint/vmlinuz"
else
	echo "Error: /boot/$kernelfilename not found"
fi

# Rewrite initrd.img on BOOT
if [ -f "/boot/initrd-$kver.img" ]; then
	cp -f "/boot/initrd-$kver.img" "$bootmountpoint/initrd.img"
else
	echo "Error: /boot/initrd-$kver.img not found"
fi

# Rewrite cmdline.txt on BOOT
grep -A 5 "$kver" "$extlinuxconf" | grep 'append' | sed 's/^\s\+append\s\+//' |
	sed "s/$defaultdelparam//" > "$bootmountpoint/cmdline.txt"

# Backup config.txt for the first time only
[ -f "$bootmountpoint/config.bkp" ] ||
  cp "$configpath" "$bootmountpoint/config.bkp"

# Delete strings with default name
sed -i '/^kernel=vmlinuz$/d ; /^device_tree=bcm2711-rpi-4-b.dtb$/d ; /^initramfs initrd.img followkernel$/d ; /^cmdline=cmdline.txt/d' \
	"$configpath"
# Make comments from strings with not default name. They could be created by the user.
sed -i 's/^kernel=/# kernel=/ ; s/^device_tree=/# device_tree=/ ; s/^initramfs /# initramfs / ; s/^cmdline=/# cmdline=/' \
	"$configpath"
echo "kernel=vmlinuz" >> "$configpath"
echo "initramfs initrd.img followkernel" >> "$configpath"
echo "cmdline=cmdline.txt" >> "$configpath"
