#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-only
#
# initramfs-tools hook: put scradle into the initrd.
#
# Installed as /usr/share/initramfs-tools/hooks/scradle. Runs at
# `update-initramfs` time on the operator's machine, not at boot, so a
# failure here is a loud build error on a terminal and never an unbootable
# machine. The runtime half is scripts/local-top/scradle.
#
# `set -e` is deliberate *here* and deliberately absent from the boot-time
# helper: at build time, half an initrd is worse than a refused one.

set -e

PREREQ=""
prereqs() { echo "$PREREQ"; }
case "${1:-}" in
prereqs)
	prereqs
	exit 0
	;;
esac

. /usr/share/initramfs-tools/hook-functions

# No configuration, nothing to do. Adding the module and the tool to every
# initrd on the machine for a feature nobody switched on is bloat with a
# blast radius, and it would also mean insmod'ing an out-of-tree module into
# every boot of a machine that never asked.
if [ ! -r /etc/scradle/boot.conf ] || \
   ! grep -qE '^[[:space:]]*[^#[:space:]]' /etc/scradle/boot.conf; then
	exit 0
fi

# manual_add_modules fails loudly when the module is not built for this
# kernel, which is what we want: an initrd that silently lacks scradle.ko is
# an initrd that has silently stopped tracking. `|| true` is not used.
# shellcheck disable=SC2154  # $version is set by initramfs-tools' mkinitramfs
if [ -f "/lib/modules/${version}/updates/dkms/scradle.ko" ] || \
   [ -f "/lib/modules/${version}/extra/scradle.ko" ] || \
   modinfo -k "${version}" scradle >/dev/null 2>&1; then
	manual_add_modules scradle
else
	echo "scradle: no scradle.ko for kernel ${version}; boot-time tracking" \
	     "will not start on that kernel. Check the DKMS build." >&2
fi

copy_exec /usr/sbin/scradlectl /sbin/scradlectl 2>/dev/null || \
	copy_exec /usr/local/sbin/scradlectl /sbin/scradlectl

# blkid is normally already there (initramfs-tools resolves the root by UUID
# with it); the helper degrades to node paths only if it is not.
[ -x /sbin/blkid ] && copy_exec /sbin/blkid /sbin/blkid

# copy_file rather than copy_exec: the helper is a shell script, and
# copy_exec's business is binaries and the libraries they need.
copy_file script /usr/lib/scradle/scradle-boot-attach /sbin/scradle-boot-attach
chmod 755 "${DESTDIR}/sbin/scradle-boot-attach"

# The configuration is copied *into* the image. Editing /etc/scradle/boot.conf
# has no effect until update-initramfs runs again; USAGE.md says so, and the
# package's postinst runs it for you when it changes the file itself.
mkdir -p "${DESTDIR}/etc/scradle"
cp /etc/scradle/boot.conf "${DESTDIR}/etc/scradle/boot.conf"

exit 0
