#!/usr/bin/env bash

if [[ -n "${KERNEL_INSTALL_INITRD_GENERATOR:-}" ]]; then
	exit 0
fi

prune_orphaned_fallbacks() {
	local fallback pkgbase

	shopt -s nullglob
	for fallback in /boot/initramfs-*-fallback.img; do
		pkgbase="${fallback#/boot/initramfs-}"
		pkgbase="${pkgbase%-fallback.img}"

		if [[ -e "/boot/vmlinuz-${pkgbase}" ]]; then
			continue
		fi

		if grep -qxF -- "${pkgbase}" /usr/lib/modules/*/pkgbase 2>/dev/null; then
			continue
		fi

		echo "--> Removing orphaned fallback initramfs: ${fallback}"
		rm -f "${fallback}"
	done
	shopt -u nullglob
}

if [[ "${1:-}" == "--prune" ]]; then
	prune_orphaned_fallbacks
	exit 0
fi

while read -r line; do
	if [[ "$line" == 'usr/lib/modules/'+([^/])'/pkgbase' ]]; then
		read -r pkgbase <"/${line}" || continue
		rm -f "/boot/vmlinuz-${pkgbase}" \
			"/boot/initramfs-${pkgbase}.img" \
			"/boot/initramfs-${pkgbase}-fallback.img"
	fi
done
