#!/bin/bash
#LAUNCH_FORK
# Note: the above token is consumed by the parent script and causes
# this script to be forked rather than sourced.
#
#################################################################################################
# Script.....: /usr/share/hwm-configure/platform/aarch64/installer/helper.scr/002-rpi_bl-configure
# Called from: /usr/lib/setup/armedslack-postinstall-scripts/001-hwm-os-configure
# Purpose....: Configure the Raspberry Pi Native Boot Loader for the supported Raspberry Pi
#              Hardware Models.
# Version....: 1.01
# Date.......: 25-Apr-2026
# Author.....: Stuart Winter <mozes@slackware.com>
#################################################################################################
# Change log
# v1.01, 25-Apr-2026
# * RPi Boot Loader config files are now copied from the installer initrd, rather than from the
#   SD card's fat partition. This enables users to decouple their OS from the SD card.
# v1.00, 19-Oct-2025
# * Initial version
#################################################################################################
#
# Copyright 2025-2026  Stuart Winter, Earth, Milky Way, "".
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################################

# Only install and configure U-Boot if the Kernel cmdline operator 'bl_rpi' is present.
# This enables us to easily determine whether we're meant to configure the RPi Boot Loader
# on this Hardware Model, rather than perform a number of tests on the presence of files, etc.
# We exit silently without error if the cmdline token isn't present, since this doesn't constitute
# an error.
cmdline_has bl_rpi || exit 0

# Files in play:
# /mnt/boot/platform/hwm_bw/slkos.cmdline.txt: OS version of cmdline.txt, to be moved into place
# /mnt/boot/platform/hwm_bw/slk_config.txt: subst slk_initrd-armv8.img -> slk_initrd-armv8

# Location of the root file system:
T_PX=$1
# Installer's temporary location:
TMP=${TMP:-/var/log/setup/tmp}

# Determine the Hardware Model name:
export HWM=$( slk-hwm-discover )
# Determine archtecture:
ARCH=$( slk-hwm-discover --print-arch )

# The Boot Loader configuration template:
RPIBL_TEMPLATES_DIR=/usr/share/hwm-configure/platform/${ARCH}/installer/assets/bootloader/rpi
[ ! -d ${RPIBL_TEMPLATES_DIR} ] && exit 1

# Global settings applicable to all Hardware Models:
#
# Determine the root file system type set for this installation.
# This is stored earlier in the installation process by
# /usr/lib/setup/armedslack-SeTpartitions
[ -s ${TMP}/root_sys_type ] && conf_root_fstype="$( < ${TMP}/root_sys_type )"

# Root device's file system label:
# Note: future possibility: need to handle statically set '--label SLKroot' within
# the grub template config file. Not worth the effort unless people start going crazy
# customising stuff.
[ -s ${TMP}/SeTrootdev_labeled ] && conf_root_dev="$( < ${TMP}/SeTrootdev_labeled )"

# Config files:
# Primary RPi native BL config:
SLK_PRIMARY_RPI_BL_CONF=${T_PX}/boot/platform/hwm_bw/config.txt
# Slackware config that's included in the main RPi BL config, /boot/platform/hwm_bw/config.txt
SLK_RPI_BL_CONF=${T_PX}/boot/platform/hwm_bw/slk_config.txt
# Bundled template ready for editing:
SLK_RPI_BL_CMDLINECONF=${T_PX}/boot/platform/hwm_bw/slkos.cmdline.txt
# Production/live target file:
# Don't prefix with ${T_PX}, since we want surface it within the dialog box.
RPI_BL_CMDLINECONF=/boot/platform/hwm_bw/cmdline.txt

# Set the console according to the Hardware Model:
# Maybe needed in the future if for some odd reason the serial console changes
# between RPi Hardware Models.
#case "${HWM}" in
#   "Raspberry Pi"*)
#      hwmconsole="console=tty1" ;;
#esac

# Default set of Kernel cmdline options:
APPEND_KERNELCMDLINE=""

# Kernel printk and system messages are sent to both the Linux virtual console and
# serial port.
if [ -f /.is-rpi-kernel-fork ]; then
   # RPi vendor fork uses ttyS0:
   # +=" 8250.nr_uarts=1 "  <-- doesn't appear to be necessary in either Kernel
   #APPEND_KERNELCMDLINE+=" console=ttyS0,115200 console=tty1 "
   APPEND_KERNELCMDLINE+=" console=serial0,115200 console=tty1 "
 else
   # The mainline Kernel uses ttyS1:
   APPEND_KERNELCMDLINE+=" console=ttyS1,115200 console=tty1 "
fi

# REMOVED:No need to do this as we have the best console settings by default.
#
# Don't offer this if you're not installing from the virtual console:
# Might want to re-add this test - not sure yet.
#( tty | grep -Eq '^/dev/tty[0-9]' ) || exit 0
#   --cursor-off-label \
#dialog \
#   --backtitle "Console Setting" \
#   --defaultno \
#   --colors \
#   --title "CONFIGURE CONSOLE SETTINGS" \
#   --yes-label "HDMI" \
#   --no-label "Serial" \
#   --yesno \
#"\nYou may now configure the console settings of your ${HWM}\n
#\nSelect where you want the system console to appear.\n\n
#\nSelect \Zb\Zr\Z8 HDMI \Z1\Zn if you are using only an HDMI monitor.\n
#\nSelect \Zb\Zr\Z8 Serial \Z1\Zn if you are using only the serial console (UART) or both.\n
#\
#\nThese settings can be changed later within the boot loader configuration:\n
#\Z4\Zb${RPI_BL_CMDLINECONF}\Z0\ZB
#\n\nRecommendation: Serial" 20 80
#[ $? = 0 ] && APPEND_KERNELCMDLINE+=" ${hwmconsole} " # user chose 'HDMI'

dialog \
   --backtitle "Bootware" \
   --sleep 3 \
   --infobox "Configuring Boot Loader..." 3 30

# Install the templates contained within the Slackware Installer:
# The primary config file:
install -Dpm644 ${RPIBL_TEMPLATES_DIR}/config.txt ${SLK_PRIMARY_RPI_BL_CONF}
# The Slackware config file (activated thru an 'include' directive in config.txt):
install -Dpm644 ${RPIBL_TEMPLATES_DIR}/slk_config.txt ${SLK_RPI_BL_CONF}
# The Kernel cmdline config (installed as 'cmdline.txt')
install -Dpm644 ${RPIBL_TEMPLATES_DIR}/slkos.cmdline.txt ${T_PX}/${RPI_BL_CMDLINECONF}

# Set the root file system type & location to those configured in the Installer.
# The shipped template has placeholders - %ROOTDEV%, %ROOTFSTYPE%
sed -i 's?%ROOTDEV%?'"${conf_root_dev}"'?g' ${T_PX}/${RPI_BL_CMDLINECONF}
sed -i 's?%ROOTFSTYPE%?'"${conf_root_fstype}"'?g' ${T_PX}/${RPI_BL_CMDLINECONF}

# Switch the Installer initrd image name -> OS InitRD:
# This is editing the config file, not the cmdline.txt:
sed -i 's?slk_initrd-armv8.img?slk_initrd-armv8?g' ${SLK_RPI_BL_CONF}

# Remove any references to RPi Hardware Model variant 'cmdline.txt' configs.
# These may be used if we need to diverge from a generic set of cmdline.txt settings
# for any particular RPi Hardware Model variant.
# An example is where the RPi Kernel fork on the RPi5 requires different console=
# settings than the RPi5.  In order to provide a generic Slackware Installer image,
# we can instruct the RPi Boot Loader to use a separate cmdline.txt.  The Installer's
# post-installation script (this one) will handle properly configuring the OS's cmdline.txt;
# we just need to get us into the Installer first.
# Remove all instances of this throughout the primary BL config:
sed -i '/^cmdline=slk_inst_rpi[0-9][0-9a-zA-Z]*_cmdline\.txt$/d' ${SLK_PRIMARY_RPI_BL_CONF}
# Delete them as they're not required after installation:
rm -f ${T_PX}/boot/platform/hwm_bw/slk_inst_rpi*_cmdline.txt

# If the user wants to enable the await root device feature, they can
# set a flag from the shell ( $ touch /.enableawaitrootdev ) and we'll add it:
if [ -f /.enableawaitrootdev ]; then
   #echo "...enabling awaitrootdev OS InitRD feature"
   APPEND_KERNELCMDLINE+=" awaitrootdev "
fi

# Apply Kernel cmdline options, substituting the place holder:
# Here we typically configure the console= settings for the particular Hardware Model.
sed -i 's?%POST_INST_OS_CMDLINE_APPEND%?'"${APPEND_KERNELCMDLINE}"'?g' ${T_PX}/${RPI_BL_CMDLINECONF}
sleep 2
clear
