#! /bin/sh
set -e

ESP_LIST="/etc/kernel/proxmox-boot-uuids"
ESPTYPE='c12a7328-f81f-11d2-ba4b-00a0c93ec93b'

MANUAL_KERNEL_LIST="/etc/kernel/proxmox-boot-manual-kernels"
PINNED_KERNEL_CONF="/etc/kernel/proxmox-boot-pin"
NEXT_BOOT_PIN="/etc/kernel/next-boot-pin"

MOUNTROOT="${TMPDIR:-/var/tmp}/espmounts"
# relative to the ESP mountpoint
PMX_ESP_DIR="EFI/proxmox"
PMX_LOADER_CONF="loader/loader.conf"
GRUB_PIN_SNIPPET="/etc/default/grub.d/proxmox-kernel-pin.cfg"

# adapted from /etc/kernel/postinst.d/apt-auto-removal as present in
# debian's apt package:
#
# Mark as not-for-autoremoval those kernel packages that are:
#  - the currently booted version, if still installed
#  - the kernel version we've been called for
#  - the latest kernel version (as determined by debian version number)
#  - the second-latest kernel version
#  - the latest kernel version of each series (e.g. 4.13, 4.15, 5.0) by
#    marking the meta-packages
#  - the currently pinned kernel if any

kernel_keep_versions() {
	eval "$(apt-config shell DPKG Dir::bin::dpkg/f)"
	test -n "$DPKG" || DPKG="/usr/bin/dpkg"

	list="$("${DPKG}" -l | awk '/^[ih][^nc][ ]+(proxmox|pve)-kernel-[0-9]+\./ && $2 !~ /-dbg(:.*)?$/ && $2 !~ /-dbgsym(:.*)?$/ { print $2; }' \
	   | sed -e 's#^pve-kernel-##' -e 's#^proxmox-kernel-##' -e 's#-signed$##' -e 's#:[^:]\+ # #')"

	sorted_list="$(echo "$list" | sort --unique --reverse --version-sort)"

	[ -n "$1" ] && install_version="$1"

	running_version="$(uname -r | tr 'A-Z' 'a-z')"

	# ignore the currently running version if attempting a reproducible build
	if [ -n "${SOURCE_DATE_EPOCH}" ]; then
		running_version=""
	elif [ ! -e "/boot/vmlinuz-$running_version" ]; then
		# ignore the current version if it got removed, the "auto-remove" logic
		# will not be affected, because either it is installed and thus we keep
		# it in the list, or it's already removed anyway
		running_version=""
	fi

	latest_2_versions="$(echo "$sorted_list" | grep -E '^[^ ]+-pve' | head -n2 )"

	series_metapackages="$(echo "$sorted_list" | grep -Ev '^[^ ]+-pve' | head -n2)"

	oldseries="$(echo "$series_metapackages" | tail -n1)"
	oldseries_latest_kernel="$(echo "$sorted_list" | grep -E "^${oldseries}\.[^ ]+-pve" | head -n1 )"

	if [ -e "$MANUAL_KERNEL_LIST" ]; then
		manual_kernels="$(cat "$MANUAL_KERNEL_LIST")"
	fi

	pinned_kernel="$(get_first_line "$PINNED_KERNEL_CONF")"
	nextboot_kernel="$(get_first_line "$NEXT_BOOT_PIN")"

	kernels="$(cat <<-EOF
		$running_version
		$install_version
		$manual_kernels
		$latest_2_versions
		$series_metapackages
		$oldseries_latest_kernel
		$pinned_kernel
		$nextboot_kernel
		EOF
	)"

	echo "$kernels" | sort -u | sed -e '/^$/ d'
}

#bootable kernels are the same as the no_autoremove ones without the meta-package
boot_kernel_list() {
	list="$(kernel_keep_versions "$@")"

	echo "$list" | grep -vE '^[0-9]+\.[0-9]+$' || true
}

warn() {
	echo "$@" 1>&2
}

reexec_in_mountns() {
	if [ -z "$PVE_EFIBOOT_UNSHARED" ]; then
		export PVE_EFIBOOT_UNSHARED=1
		echo "Re-executing '$0' in new private mount namespace.."
		unshare --mount --propagation private "$0" "$@"
		exit 0
	fi
}

loop_esp_list() {
	if [ ! -e ${ESP_LIST} ]; then
		return 2
	fi

	cat "${ESP_LIST}" | while IFS= read -r curr_uuid; do
		if [ -z "$curr_uuid" ]; then
			continue
		fi
		"$@"
	done
}

get_first_line() {
	file="$1"
	if [ ! -e  "$file" ]; then
	    echo ""
	    return
	fi

	while IFS= read -r line || [ -n "$line" ]; do
		break
	done < "${file}"
	echo "$line"
}

set_grub_default() {
	kver="$1"

	if [ -z "${kver}" ]; then
		rm -f "${GRUB_PIN_SNIPPET}"
	else
		# grub menu entry ids contain the internal root-device id (e.g. for zfs the GUID of
		# the pool printed in hex) as this is independent of the ESP (or grub location)
		# take it from /boot/grub/grub.cfg
		root_devid=$(sed -rn "s/.*gnulinux-advanced-(.+)['] \{$/\1/p" \
			/boot/grub/grub.cfg)
		entry="gnulinux-advanced-${root_devid}>gnulinux-${kver}-advanced-${root_devid}"
		echo "GRUB_DEFAULT=\"${entry}\"" > "${GRUB_PIN_SNIPPET}"
	fi
}

set_systemd_boot_default() {
	mountpoint="$1"
	kver="$2"
	if [ -z "${kver}" ]; then
		entry="proxmox-*"
	else
		entry="proxmox-${kver}.conf"
	fi

	# replaces the current default entry, if one exists else append it at the end of the file
	sed -ri "/^default /{h;s/ .*\$/ ${entry}/};\${x;/^$/{s//default ${entry}/;H};x}" \
		"${mountpoint}/$PMX_LOADER_CONF"

}
