#!/bin/bash
# Written by Didier Spaier this script is dedicated to the public domain.
#
# This script is called by slapt-get --upgrade like this:
#
# Its main purpose is to  perform specific actions when upgrading kernels
# Rationale: we want to make sure that a working kernel be always installed, but
# we don't want to keep more kernels than necessary, to save space on disk and
# not clutter the GRUB boot menu. In that aim:
# 1. When installing a new kernel, we will keep the running one.
# 2. When the new kernel runs, we remove the one that was running when
#    installing it.
# Additionally, this script uses spkg -i then spkg -d for packages that ship
# many files, namely kernel-modules and kernel-source, to save time removing
# them as spkg -d is faster that removepkg. This could be used to upgrade other
# packages with many files that do not need a pre-installation. In case of
# packages kernel-generic or kernel-modules it calls update-portable that will
# make a specific initrd and grub.cfg case occuring, else make an initrd and
# update grub directly.
# Incidentally, we plan to not upgrade the huge kernel anymore. As soon as a
# generic one will be running we will remove the one initially installed upon
# next upgrade of a generic kernel.
# shellcheck disable=SC2001
LOG=/tmp/wrapupgradepkglog
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.
installthepackage() {
	[ "$PKGSHORTNAME" = aaa_base ] && upgradepkg "$PKGPATH" && return
	[ "$PKGSHORTNAME" = kernel ] && installpkg "$PKGPATH" && rmobsolete && initrdandgrub && return
	[ "$PKGSHORTNAME" = kernel-headers ] && installpkg "$PKGPATH" && rmobsolete && return
	[ "$PKGSHORTNAME" = kernel-source ] && installpkg "$PKGPATH" && rmobsolete && return
	spkg -u --reinstall "$PKGPATH"
}
rmobsolete() {
	# We remove all packages kernel, kernel-source and kernel headers that are
	# neither just installed nor with a version number equal to that of the running
	# kernel
	(cd /var/lib/pkgtools/packages || exit
	INSTALLED=$(find . -type f|grep "${PKGSHORTNAME}-[^-]*-[^-]*-[^-]*$"|sed 's#..##'|grep -v "$PKGVERSION")
	echo "$INSTALLED"|while read -r i; do
		iVERSION=$(echo "$i"|sed "s/.*-\($FRAG\)-$FRAG-$FRAG$/\1/")
		if [ "$iVERSION" = "$RUNNINGVERSION" ]; then
			echo "not removing $i" >>$LOG
			continue
		fi
		echo "spkg -d $i" >>$LOG
		spkg -d "$i"
	done
	)
	# Remove the symlinks we won't use any more
}
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 that grub we suggest that you install grub now."
		echo
	else
		gettext "Updating GRUB..."
		echo
		update-grub
		echo "update-grub" >>"$LOG"
		echo
	fi
}
installthepackage
