#!/bin/bash
shopt -s extglob

# Copyright 2016-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.

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

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

# Determine whether we're in /patches or in a stable release:
if slack_findpkgstore_is_stablerelease ; then
   # Is set by default in /usr/share/slackdev/slackdev.config as ${SLACKSOURCE:-$HOME/slackware64-15.0/patches/source}
   slacksource=$SLACKSOURCE/../packages/
 else
   # Pull the Slackware x86 package from the package repo dir 'a' series:
   slacksource=$SLACKSOURCE/../slackware*/a/
fi

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

cd $PKG

# Unpack Slackware package:
# The firmware blobs are arch neutral anyway so I'll just copy Slackware's package.
echo "Unpacking Slackware upstream kernel-firmware package.."
tar xf $slacksource/kernel-firmware-*.t?z -C. || failextract
# Set up symlinks:
grep -E '^\( cd .*(rm|ln)' install/doinst.sh | bash

# Walk the host architecture, calling the helper scripts to
# populate the package with the relevant firmware blobs.
# At this juncture, it's worth pointing out that the ARM and AArch64
# 'kernel-firmware' packages will diverge.
# The firmware package is already huge and I'd like to avoid adding
# what I know up front is unnecessary bloat.
mkdir -vpm755 $PKG/lib/firmware
for platformdir in $( find $PORTCWD/platform/$SLKPORTARCH -type d -mindepth 1 -maxdepth 1 ) ; do
   soc=$( basename $platformdir )
   if [ -f $platformdir/$soc ]; then
      echo "Adding firmware for platform: $SLKPORTARCH , SoC: $soc"
      . $platformdir/$soc
   fi
done

# Clean up some x86 only stuff:
rm -fv $PKG/boot/amd-ucode.img
rmdir $PKG/boot

slackhousekeeping

# Make our package:
slackmp  # run makepkg -l y -c n
