#!/bin/sh
# This script apply the kernel upgrades from Slint.
# This script, written from scratch, is dedicated to the public domain.
# Didier Spaier <didier~at~slint.fr>

# What's is done:
# First we check that there is a kernel package installed that should
# be upgraded, else we bail out.
# a) if you didn't install grub when installing Slint, because grub was
# already installed in another distribution, you should run update-grub
# from this other distribution.
# b) the script /usr/sbin/upgrade-kernel is only intended to upgrade
# kernels provided by Slint, not custom ones.

# 28 August 2020 - install instead of upgrade the new packages if no kernels
# of the same kind (generic or huge) at the same major kernel version are found
# in /boot
export TEXTDOMAIN=slint
. gettext.sh
gettext "Please wait..."
echo
slapt-get -u 1>/dev/null
kernel_packages=$(slapt-get --upgrade -s 2>/dev/null|grep kernel)
# If no
if [ "$kernel_packages" = "" ]; then
	gettext "All kernel packages provided by Slint are up to date."
	echo
	exit
fi
# slapt-get -i proposes to replace a package at another version even if
# the "new" package is already installed. We do not want that, which can
# occur if a package not shipped in Slint is also installed.
kernel_list=""
for i in $kernel_packages; do
	target=$(slapt-get -i -s $i|grep ^kernel|sed "s/.* //")
	if ! ls /var/log/packages/|grep -q ${i}-$target; then
		kernel_list="$kernel_list $i"
	fi
done
if [ "$kernel_list" = "" ]; then
	gettext "Nothing to do."
	echo
	exit
fi
# The output of next command lists the packages that would be replaced
# and those that would replace them, without actually replacing yet.
slapt-get -i -s $kernel_list|grep ^kernel
gettext "Do you agree? "
echo
read -p "[y/N] " answer
if [ ! "$answer" = "y" ] && [ ! "$answer" = "Y" ]; then
	gettext "Nothing done."
	echo
	exit
fi
echo "kernel_list=$kernel_list"
for i in $kernel_list; do
	kernel=$i
	if echo $kernel|grep -q kernel; then
		pkgpath=$(slapt-get --print-uris -i -s  $kernel|tail -n 1)
		pkgname=$(basename $pkgpath)
		slapt-get -i -d $kernel
		# wrapupgradepkg expect the path to the new packages as $2
		# for consistency with other callers, hence the dummyargument.
		wrapupgradepkg dummyargument /var/slapt-get/slint/$pkgname
	fi
done
