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

# mkinitd.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter <mozes@slackware.com>
# 21-Nov-2004 - 2021
#
# Copyright 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018, 2021  Patrick J. Volkerding, Sebeka, MN, USA
#
# 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

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

# Write a warning to stdout if the mkinitrd script has a different version:
eval $( grep "^MKINITRD_VERSION=" $CWD/mkinitrd )
if [ "$VERSION" != "$MKINITRD_VERSION" ]; then
  echo "The version of this package ($VERSION) is not equal to the version of the mkinitrd script ($MKINITRD_VERSION)."
  sleep 5
fi

# Versions of bundled packages:
# To save on maintenance, and since we carry the same versions as x86 Slackware,
# let's pull the version numbers from the x86 trunk:
slack_setvarfromupstream BB

##### Build busybox #############################################

# Extract source:
tar xf $CWD/busybox-$BB.tar.!(*sign|*asc|*sig)
#tar xvvf $PORTCWD/sources/busybox-$BB.tar.!(*sign|*asc|*sig)
cd busybox-* || failextract
slackhousekeeping

# Apply any patches:
if [ -d $CWD/fixes-$BB ]; then
  for pfile in $CWD/fixes-$BB/*.patch ; do
    patch -p1 < $pfile || exit 1
  done
fi

# Fix ARM build problem:
auto_apply_patch $PORTCWD/patches/ftbfs-v1.37.diff || failpatch

# Configure:
install -vpm644 $CWD/busybox-dot-config .config
# Copy the local copy - we do this only if we're using a different version from Slackware x86
# (which may be because the version in x86 won't build on ARM)
if [ -f $PORTCWD/sources/busybox-dot-config ]; then
   echo "******* WARNING: Using local busybox config *******"
   sed -e \
  's#^CONFIG_PREFIX=.*#CONFIG_PREFIX="'$PKG'/usr/share/mkinitrd/initrd-tree"#' \
  $PORTCWD/sources/busybox-dot-config > .config
fi

make oldconfig || failconfig

# Build:
make $NUMJOBS || make || failmake

mkdir -p $PKG/usr/share/mkinitrd/initrd-tree/{bin,sbin}
make install || failinstall
cd _install
cp --remove-destination -fav * $PKG/usr/share/mkinitrd/initrd-tree
cd ..
rm -f $PKG/usr/share/mkinitrd/initrd-tree/linuxrc

# Add a poor-man's reboot into the initrd.
# This is because if there is a problem and your initrd can't mount
# the filesystems, then 'reboot' won't work; and most terminal emulators
# disconnect when you power cycle the device, which may cause you to miss
# being able to interrupt the boot sequence.
#mkdir -vpm755 $PKG/sbin
#echo 'echo b > /proc/sysrq-trigger' > $PKG/sbin/freboot
#chmod 755 $PKG/sbin/freboot

# Copying additional files:
cp -fav $CWD/mkinitrd_command_generator.sh $PKG/usr/share/mkinitrd
chown root:root $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh
chmod 755 $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh
cp -fav $CWD/keymaps.tar.!(*sign|*asc|*sig) $PKG/usr/share/mkinitrd
chown root:root $PKG/usr/share/mkinitrd/keymaps.tar.!(*sign|*asc|*sig)
chmod 644 $PKG/usr/share/mkinitrd/keymaps.tar.!(*sign|*asc|*sig)

# Zip up the initrd-tree:
( cd $PKG/usr/share/mkinitrd/initrd-tree
  tar xf $CWD/_initrd-tree.tar.!(*sign|*asc|*sig) || exit 1
  cat $CWD/init > init

  # Patch init:
  zcat $CWD/0001-Fix-LUKSTRIM-with-C-T-and-UUID.patch.gz | patch -p1 --verbose || exit 1
  rm -f init.orig

  # Add Slackware ARM stuff:
  mknod -m 644 dev/random c 1 8
  mknod -m 644 dev/urandom c 1 9

  # Archive it:
  tar czf ../initrd-tree.tar.gz .
)
rm -rf $PKG/usr/share/mkinitrd/initrd-tree

# Add busybox docs:
mkdir -p $PKG/usr/doc/busybox-$BB
cp -a AUTHORS COPYING* INSTALL LICENSE README* TODO* \
  $PKG/usr/doc/busybox-$BB
cp -a e2fsprogs/README $PKG/usr/doc/busybox-$BB/README.e2fsprogs
cp -a libbb/README $PKG/usr/doc/busybox-$BB/README.libbb
cp -a shell/README $PKG/usr/doc/busybox-$BB/README.shell
cp -a testsuite/README $PKG/usr/doc/busybox-$BB/README.testsuite

# Install mkinitrd:
mkdir -p $PKG/sbin
cp -a $CWD/mkinitrd $PKG/sbin/mkinitrd
chown root:root $PKG/sbin/mkinitrd
chmod 755 $PKG/sbin/mkinitrd

# Patch to switch to mktemp:
( cd $PKG/sbin ; zcat $CWD/mkinitrd.tempfile.to.mktemp.patch.gz | patch --verbose || exit 1) || exit 1
# Patch mkinitrd to bail on no temp directory:
( cd $PKG/sbin ; zcat $CWD/0002-bail-if-temp-dir-is-not-created.patch.gz | patch -p1 --verbose || exit 1) || exit 1
# Don't include 40-usb_modeswitch.rules on the initrd:
( cd $PKG/sbin ; zcat $CWD/0003-blacklist.40-usb_modeswitch.rules.patch.gz | patch -p1 --verbose || exit 1) || exit 1
# Support modules compressed with xz:
( cd $PKG/sbin ; zcat $CWD/0005-support-modules-compressed-with-xz.patch.gz | patch -p1 --verbose || exit 1) || exit 1
# Ensure target directory for the module exists (cp regression workaround for coreutils-9.1):
( cd $PKG/sbin ; zcat $CWD/0006-coreutils-9.1-ensure-target-dir-exists.patch.gz | patch -p1 --verbose || exit 1) || exit 1
rm -f $PKG/sbin/mkinitrd.orig
# Use -R if we detect the root partition is a partition of a RAID device:
( cd $PKG/usr/share/mkinitrd ; zcat $CWD/0004-check-if-BASEDEV-is-a-partition-of-a-RAID-volume.patch.gz | patch -p1 --verbose || exit 1) || exit 1
rm -f $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh.orig
# Fix for kmod-30:
( cd $PKG/sbin ; zcat $CWD/0007-kmod30.patch.gz | patch -p1 --verbose || exit 1) || exit 1
# Bugfix for previous RAID partition patch:
( cd $PKG/usr/share/mkinitrd ; zcat $CWD/0008-fix-check-if-BASEDEV-is-a-partition-of-a-RAID-volume.patch.gz | patch -p1 --verbose || exit 1) || exit 1
rm -f $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh.orig
# Don't include the 99-nfs.rules on the initrd:
( cd $PKG/sbin ; zcat $CWD/0009-exclude-99-nfs.rules.patch.gz | patch -p1 --verbose || exit 1) || exit 1
rm -f $PKG/sbin/mkinitrd.orig
# Fix test for including JFS or XFS repair tools:
( cd $PKG/sbin ; zcat $CWD/0010-fix-test-for-jfs-xfs-repair-tools.patch.gz | patch -p1 --verbose || exit 1) || exit 1
rm -f $PKG/sbin/mkinitrd.orig
# Fix handling of -h -l -K options for LUKS and encrypted hibernation:
( cd $PKG/usr/share/mkinitrd ; zcat $CWD/0011-fix-LUKS-handling.patch.gz | patch -p1 --verbose || exit 1) || exit 1
rm -f $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh.orig

# Superfluous on ARM:
#mkdir -p $PKG/usr/man/man{5,8}
#install -vpm644 $CWD/{mkinitrd_command_generator.8,mkinitrd.8} $PKG/usr/man/man8/
#install -vpm644 $CWD/mkinitrd.conf.5 $PKG/usr/man/man5/

# Not for ARM - we ship a generic initrd for the supported systems, so there's
# no need to build one in the installer; plus the generation script would need
# a fair amount of work to detect everything required (last time I checked in ~2017 anyway!)
# It'd probably need a static list of base requirements + whatever it found at runtime, and some
# de-dupes.
#mkdir -p $PKG/var/lib/pkgtools/setup
#install -vpm755 $CWD/setup.01.mkinitrd $PKG/var/lib/pkgtools/setup/

mkdir -p $PKG/usr/sbin
#install -vpm755 $CWD/geninitrd $PKG/usr/sbin/
# Not implemented on arm - issue a notice:
install -vpm755 $PORTCWD/sources/geninitrd $PKG/usr/sbin/

mkdir -p $PKG/etc
# Don't install because this is superfluous on ARM.
#install -vpm644 $CWD/mkinitrd.conf.sample $PKG/etc/
mkdir -p $PKG/etc/default
install -vpm644 $CWD/geninitrd.default $PKG/etc/default/geninitrd.new

# ARM systems often need more time to find devices, so we'll adjust
# the sample config file:
case "$( uname -m )" in
  arm*) sed -e 's@#WAIT="1"@#WAIT="4"@g' -i $PKG/etc/mkinitrd.conf.sample;;
esac

# mkinitrd isn't user-facing on ARM, we use os-initrd-mgr.
# However, mkinitrd is still used by the Kernel build script, so
# we'll make it quit unless a shell variable is set:
sed -i '\?^MKINITRD_VERSION=? i\[ -z "$MKINITRD_ALLOWEXEC" ] && { echo "$0 is not implemented on ARM. See os-initrd-mgr(8) for details."; exit 1 ;}' $PKG/sbin/mkinitrd || failpatch

# Add documentation:
mkdir -p $PKG/usr/doc/mkinitrd-$VERSION
sed $CWD/README.initrd \
  -e "s,@DATE@,$(date),g" \
  -e "s,@KERNEL_VERSION@,$(uname -r),g" \
  -e "s,@PACKAGE_VERSION@,$(uname -r | tr - _),g" \
  -e "s,@LILO_KERNEL_NAME@,$echo $(uname -r) | tr -d . | tr -d - ),g" \
  -e "s,@MKINITRD_VERSION@,$VERSION,g" \
  -e "s,@ARCH@,$ARCH,g" \
  -e "s,@BUILD@,$BUILD,g" \
  > $PKG/usr/doc/mkinitrd-$VERSION/README.initrd
# OK so there's no point in doing the above sedding, but I keep it in the build script
# so I won't wonder why it's missing from script if I ever do a comparison between the x86 version.
# Replace the readme with the ARM version:
install -vpm644 $PORTCWD/README.initrd.arm $PKG/usr/doc/mkinitrd-$VERSION/README.initrd

# In ARM, we don't ship /boot/boot/remove-orphaned-initrds:
#  /boot/remove-orphaned-initrds: this script will remove initrds found in /boot
#  if there is no matching kernel version found. This can be run manually or
#  added as a cron job to prevent unneeded initrds from filling up /boot.
#cp -a $CWD/remove-orphaned-initrds $PKG/boot
#chown root:root $PKG/boot/remove-orphaned-initrds
#chmod 755 $PKG/boot/remove-orphaned-initrds
#( cd $PKG/usr/sbin ; ln -sf /boot/remove-orphaned-initrds . )

# Replace the mkinitrd wrapper with a dummy, since this cannot be used
# on Slackware ARM / AArch64.
sed -e 's?%ARCH%?'"$SLKPORTARCH"'?g' \
    -e 's?%VERSION%?'"$VERSION"'?g' \
    $PORTCWD/sources/mkinitrd_command_generator.sh \
    > $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh
chmod 755 $PKG/usr/share/mkinitrd/mkinitrd_command_generator.sh

mkdir -vpm755  $PKG/boot
( cd $PKG/boot
  ln -vsf ../usr/doc/mkinitrd-$VERSION/README.initrd . )

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

# Apply generic Slackware packaging policies:
cd $PKG
slackstripall   # strip all .a archives and all ELFs
slack_delete_lafiles # delete usr/lib{,64}/*.la
slackgzpages -i # compress man & info pages and delete usr/info/dir
slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
slackdesc       # install slack-desc and doinst.sh
slackmp         # run makepkg -l y -c n

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