#!/bin/bash
# Written by Didier Spaier this script is dedicated to the public domain.
#
# This script is called by slapt-get --install:
#
# Its main purpose is to  perform specific actions when upgrading kernels.
# shellcheck disable=SC2001
LOG=/tmp/wrapinstallpkglog
date >>$LOG
echo "running $0" >> $LOG
RUNNINGVERSION=$(uname -r)
# We are called with the path to the new package as $2
PKGPATH="$2"
PKGNAME="$(basename "$PKGPATH")"
unset KERNEL 
#if echo PKGNAME|grep -q ^kernel-[[:digit:]]; then
#	KERNELNAME=${PKGNAME#boot/}
#fi
FRAG='[^-]\{1,\}'
PKGSHORTNAME="$(echo "$PKGNAME"|sed "s/\(.*\)-$FRAG-$FRAG-$FRAG$/\1/")"
PKGVERSION="$(echo "$PKGNAME"|sed "s/.*-\($FRAG\)-$FRAG-$FRAG$/\1/")"
KEYFILE=crypto_keyfile.bin
unset ENCRYPT
if [ "$(lsblk -lno type "$(findmnt -lno source /|cut -d[ -f1)")" = "crypt" ]; then
	if [ ! -f /etc/keys/$KEYFILE ]; then
		echo \
"WARNING $KEYFILE not found!
You will have to type the passphrase during boot to unlock the root partition!
Read  \"man dracut\" to know more."
		sleep
	fi
	ENCRYPT=yes
fi

# We assume that only one kernel package at a given version is installed. As a
# consequence, if we need to reconfigure a kernel, better wait for a new version
# or at least do not do that twice in a row, else we won't know which kernel
# package to remove short of checking the oldest installed according to
# "stat -c %Y $i" that you could insert below, probably an overkill.
usespkg() {
	spkg -i "$PKGPATH"
}
initrdandgrub() {
	# Called to upgrade kernel, do something as soon as installed.
	KERNELINSTALLED=$(ls /var/lib/pkgtools/packages/kernel-"$PKGVERSION"*)
	if  [ "$KERNELINSTALLED" ]; then
		if [ "$ENCRYPT" ]; then
			dracut -q --no-early-microcode --zstd --install  " /etc/keys/$KEYFILE " --kver "$PKGVERSION" 2>>"$LOG"
		else
			dracut -q --no-early-microcode --zstd --kver "$PKGVERSION" 2>>"$LOG"
		fi
		updategrub
	fi
	# Remove the stale initramfs
	(cd /boot || exit
	find . -name "initramfs*img"|sed "s#..##"|while read -r i; do
		iVERSION="$(printf "%b" "${i%.img}"|sed "s#initramfs-##")"
		if ! find . -name "vmlinuz*"|grep -q "$iVERSION"; then
			rm "$i"
			echo "stale initramfs /boot/$i removed"
		fi
	done
	)
	
}
updategrub() {
	if [ ! -f /boot/grub/grub.cfg ]; then
		echo
		gettext "It seems that you didn't install grub in Slint. If you installed it from
another distribution you should now run update-grub from this other
distribution, else Slint won't boot from the grub menu. If you used
another boot manager than grub we suggest that you install grub now."
		echo
	else
		gettext "Updating GRUB..."
		echo
		update-grub
		echo "update-grub" >>"$LOG"
		echo
	fi
}
case $PKGSHORTNAME in
	kernel) usespkg;initrdandgrub; echo "usepkg and initrdandgrub ran." >>"$LOG";;
	*) usespkg; echo "usespkg ran." >>"$LOG";;
esac
