#!/bin/bash
{
# Import DietPi-Globals ---------------------------------------------------------------
. /boot/dietpi/func/dietpi-globals
readonly G_PROGRAM_NAME='dietpi-rpi-firmware-migration'
(( $G_HW_MODEL > 9 )) && { G_DIETPI-NOTIFY 1 'You can run this script on RPi systems only!'; exit 1; }
(( $G_DISTRO > 6 )) || { G_DIETPI-NOTIFY 1 'You can run this script on Debian Bookworm or Trixie systems only!'; exit 1; }
G_CHECK_ROOT_USER
G_CHECK_ROOTFS_RW
G_CHECK_FREESPACE / 200
(( $(findmnt -nbo SIZE -T /boot) > 128000000 )) || { G_DIETPI-NOTIFY 1 'You can run this script on a system with at least 128 MiB boot partition only!'; exit 1; }
G_INIT
# Import DietPi-Globals ---------------------------------------------------------------

export DISABLE_SERVICES_START=1
/boot/dietpi/dietpi-update 1
/boot/dietpi/dietpi-services stop

# Temporary rootfs mount
G_EXEC mkdir -p rootfs
G_EXEC mount "$G_ROOTFS_DEV" rootfs

# Copy DietPi files from bootfs to rootfs
G_EXEC cp -an /boot/dietpi* rootfs/boot/
G_EXEC chmod -x rootfs/boot/dietpi{.txt,/.??*,/func/dietpi-globals}

# Remount bootfs to /boot/firmware
findmnt -M /boot &> /dev/null && G_EXEC umount /boot
G_EXEC umount rootfs
G_EXEC mkdir -p /boot/firmware
G_EXEC sed --follow-symlinks -i 's|[[:blank:]]/boot[[:blank:]]| /boot/firmware |' /etc/fstab
G_EXEC systemctl daemon-reload
findmnt -M /boot/firmware &> /dev/null || G_EXEC mount /boot/firmware

# Generate config symlinks
G_EXEC ln -sf firmware/cmdline.txt /boot/cmdline.txt
G_EXEC ln -sf firmware/config.txt /boot/config.txt

# Show kernel choice dialogue: This installs the required kernel and firmware packages and allows to select optional kernel packages for other RPi models.
until /boot/dietpi/func/dietpi-set_software rpi_kernel_choice 'dietpi-rpi-firmware-migration'; do G_WHIP_MSG '[ INFO ] A selection is required!'; done

# Remove obsolete files
G_EXEC rm -Rf /boot/firmware/{dietpi*,COPYING.linux}

G_WHIP_YESNO 'All finished!\n\nWe highly recommend to reboot, shall we reboot now?' && reboot
}