#!/bin/bash
ulimit -s unlimited
shopt -s extglob

# hwm-bw-raspberrypi.SlackBuild
# by Stuart Winter <mozes@slackware.com>
#
# Copyright 2021-2026  Stuart Winter, Donostia, Spain.
# 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.
#
# Modified by Brenton Earl
# * For EEPROM firmware and utilities

# Record toolchain & other info for the build log:
slackbuildinfo

# Paths to skeleton port's source & real Slackware source tree:
slackset_var_cwds

# Parse any command line operators:
PARAMS="$( getopt -qn "$( basename $0 )" -o P: -l pkgstoreoverride: -- "$@" )"
eval set -- "${PARAMS}"
for param in $*; do
  case "$param" in
     -P|--pkgstoreoverride) PKGSTORE_OVERRIDE="$2"
                    shift 2;;
     --) shift; break;;
  esac
done

# If the user has specified -P/--pkgstoreoverride, they want to store the resulting
# package files in a directory other than $PKGSTORE.
# We will ensure that the destination directory exists first.
[ ! -z "${PKGSTORE_OVERRIDE}" -a ! -d "${PKGSTORE_OVERRIDE}" ] && {
   echo "ERROR: Alternate package destination directory '${PKGSTORE_OVERRIDE}' does not exist"
   exit 1 ;} || { echo "Packages will be stored in: ${PKGSTORE_OVERRIDE}" ;}

# Extract package version from the firmware archive:
# This is the tag from https://github.com/raspberrypi/firmware/tree/master/boot
pushd sources
VERSION=$( ls -1 rpi-boot-fw-*.tar.xz | cut -d- -f4- | sed 's?.tar.*??g' )
VERSION2=$( ls -1 rpi-eeprom-fw-*.tar.xz | cut -d- -f4- | sed 's?.tar.*??g' )
popd

# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
export PKG=$TMP/package-$PKGNAM
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

#########################################################################
# Raspberry Pi native Boot Loader firmware, etc.
#########################################################################

# Assemble package:
mkdir -vpm755 $PKG/usr/{sbin,bin,share/$PKGNAM/bootloader-firmware}
# Install the RPi firmware:
tar xvvf $PORTCWD/sources/rpi-boot-fw-$VERSION.tar.!(*sign|*asc|*sig) \
    -C $PKG/usr/share/$PKGNAM/bootloader-firmware || failinstall

# Removed: on the RPi we now use the native BL.
## Raspberry Pi4 U-Boot Boot Loader:
## This package's doinst.sh post package install script installs the
## appropriate U-Boot 2nd stage loader as 'slk_u-boot.bin'.
## This enables upgrading of U-Boot on the RPi by simply upgrading this
## here package.
#install -vpm644 \
#   $SLACKPLATFORMDIR/bootware/bin/bcm2711/u-boot-*/bcm2711_rpi4-u-boot.bin \
#   $PKG/usr/share/$PKGNAM/bootloader-firmware/ || failinstall

#########################################################################
# rpi-eeprom utilities and firmware:
#########################################################################

#DEFAULT_RELEASE_STATUS="critical"
DEFAULT_RELEASE_STATUS="latest"
FIRMWARE_ROOT="/usr/share/$PKGNAM/eeprom-firmware/bootloader"
BOOTFS="/boot/platform/hwm_bw"

mkdir -vpm755 $PKG/${FIRMWARE_ROOT}
tar xvvf $PORTCWD/sources/rpi-eeprom-fw-$VERSION2.tar.!(*sign|*asc|*sig) \
    -C $PKG/${FIRMWARE_ROOT}/ || failinstall

pushd $PKG/$FIRMWARE_ROOT/
# Tell utilities to look in etc rather than /etc/default
sed -i 's?/etc/default/?/etc/?g' rpi-eeprom-update
sed -i 's?raspi-config?a text editor to modify /etc/rpi-eeprom-update?g' rpi-eeprom-update
# Install utilities:
install -vpm700 rpi-eeprom-{config,update,digest} $PKG/usr/bin/
rm -fv rpi-eeprom-{config,update,digest}
popd

# Create extra directories:
mkdir -vpm755 $PKG/${FIRMWARE_ROOT}/backup

mkdir -vpm755 $PKG/etc
cat << EOF > $PKG/etc/rpi-eeprom-update.new
# Release Channels:
#
# "default" / "critical" = Conservative, contains only critical fixes.
#              Most well-tested by the RPi community.
# This is the default.
#
# "stable" = More recent, may be useful if there are hardware issues
#            such as with USB devices.
#
# "beta" / "latest" = Bleeding edge, not recommended for average users.

FIRMWARE_RELEASE_STATUS="${DEFAULT_RELEASE_STATUS}"

##### WARNING: Do not edit below this line.

HWM=\$( /sbin/slk-hwm-discover )

# Determine the Hardware Model we're running on, and select the
# appropriate firmware directory:)
case \$HWM in
   "Raspberry Pi 4"*)
      slk_fwdir=2711 ;;
   "Raspberry Pi 5"*)
      slk_fwdir=2712 ;;
esac

FIRMWARE_ROOT="${FIRMWARE_ROOT}/firmware-\${slk_fwdir}"
FIRMWARE_IMAGE_DIR="\${FIRMWARE_ROOT}/\${FIRMWARE_RELEASE_STATUS}"
RECOVERY_BIN="\${FIRMWARE_ROOT}/\${FIRMWARE_RELEASE_STATUS}/recovery.bin"
FIRMWARE_BACKUP_DIR="${FIRMWARE_ROOT}/backup"
BOOTFS="${BOOTFS}"
USE_FLASHROM=0
EEPROM_CONFIG_HOOK=

# Use flashrom if available to update the bootloader without rebooting - Raspberry Pi 5
#RPI_EEPROM_USE_FLASHROM=1
EOF

###########################################################################

# Add local Slackware tools:
#install -vpm755 $PORTCWD/sources/rpi-hwm-bw-sync $PKG/usr/sbin/

# Redo the package name since the version has been updated:
# Let's just use the version set in 'arm/build' now
#export SLACKPACKAGE=$PKGNAM-$VERSION-$PKGARCH-$BUILD.txz

# If $PKGSTORE_OVERRIDE is set and exists as a directory, we'll switch
# $PKGSTORE to it so that our packages are stored outside of the main tree.
# This enables test builds of the package to be created more easily.
[ -d "${PKGSTORE_OVERRIDE}" ] && PKGSTORE="${PKGSTORE_OVERRIDE}"

# Apply generic Slackware packaging policies:
cd $PKG
slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
slackdesc       # install slack-desc and doinst.sh
slackmp -p      # run makepkg --prepend -l y -c n

# Perform any final checks on the package:
cd $PKG
slackhlinks     # search for any hard links
