#!/bin/bash
shopt -s extglob

#############################################################################################
# Script : isolinux/u-boot_tftp/build_tftp_scripts.sh
# Authors: Stuart Winter <mozes@slackware.com>
#          Brent Earl <el0226@slackware.com>
# Purpose: Build bootable U-Boot scripts that will boot the Slackware installer.
#          This facilitates
#          1) Non-destructive testing (i.e. you don't need to erase your /boot
#             partition or switch SD cards) for Kernel upgrades.
#          2) Using the Installer as a rescue environment.
# Version: 1.00
# Date...: 07-Nov-2022
#############################################################################################

TMP=$( mktemp -d ) || { echo "Failed to create temporary directory" ; exit 1 ;}

# Create a U-Boot script for a particular Hardware Model.
# $1 = DTB (Device Tree Blob) name.  This doubles as the Hardware Model name/file name.
# $2 = Suffix for the FDT base load address variable name, where required.
# $3 = Appended Linux Kernel cmdline boot args.
#      This generally isn't necessary.
function generic() {

   # Harware Model (DTB name without path and extension)
   local hwm=${1//+(*\/|.dtb)}
   echo "Generating U-Boot script for Hardware Model: $hwm"

   # Generate generic U-Boot script:
#setenv tftpblocksize 65464
   cat << EOF > $TMP/$hwm
setenv slkins_netboot "dh;dh;dh;tftp 0x1000000 slackwareaarch64-current/tftp/${hwm};source 0x1000000"
setenv slkins_netboot_pbs "dh;dh;dh;tftp 0x1000000 slackwareaarch64-current/tftp/${hwm}_pbs;source 0x1000000"
saveenv
setenv bootargs "earlyprintk root=/dev/ram rw kbd=us nic=auto:eth0:dhcp $3"
tftp \${fdt_addr$2} slackwareaarch64-current/dtb/$1
EOF
   # Continue (saves escaping the $s):
   cat << 'EOF' >> $TMP/$hwm
tftp ${kernel_addr_r} slackwareaarch64-current/Image-armv8
tftp ${ramdisk_addr_r} slackwareaarch64-current/initrd-armv8.img
EOF
   cat << EOF >> $TMP/$hwm
booti \${kernel_addr_r} \${ramdisk_addr_r}:\${filesize} \${fdt_addr$2}
EOF

   # Create a version that invokes the 'slkpbs' (pre-boot shell) for
   # debugging:
   sed 's/earlyprintk/& slkpbs/' $TMP/$hwm > $TMP/${hwm}_pbs

   # 'Compile' the script:
   for syst in $hwm ${hwm}_pbs; do
      mkimage \
         -C none \
         -A arm64 \
         -T script \
         -n "SLK Inst: $hwm" \
         -d $TMP/$syst \
         $syst
   done
}

# We no longer use U-Boot on the RPi - we use its native
# Boot Loader, and these scripts are for U-Boot.

# Raspberry Pi 4:
#generic broadcom/bcm2711-rpi-4-b.dtb
# Raspberry Pi 400:
#generic broadcom/bcm2711-rpi-400.dtb
# RockPro64:
generic rockchip/rk3399-rockpro64-v2.dtb _r
# Pinebook Pro:
# Not unless we can build the driver for the Pinebook Pro's
# docking station into U-Boot so we have Ethernet support.
#generic rockchip/rk3399-pinebook-pro.dtb _r

# Tidy
rm -rf $TMP
