#!/bin/sh
# Local variables:
# indent-tabs-mode: t
# sh-basic-offset: 8
# End:
#
# Packages that install kernels or kernel-modules create a flag
#
#   /run/regenerate-initrd/<kernel version>
#
# to have the initrd for <kernel version> generated, or
#
#   /run/regenerate-initrd/all
#
# to have all initrds generated. This script is called from posttrans
# and takes care of generating the initrds

: ${DRACUT:=/usr/bin/dracut}
if [ ! -x "$DRACUT" ]; then
    echo "${0##*/}: dracut is not installed, not rebuilding the initrd" >&2
    exit 0
fi

dir=/run/regenerate-initrd

if ! test -d "$dir"; then
	exit 0
fi
for f in "$dir"/*; do
	case $f in
	    "$dir/*")
		[ -e "$f" ] || break;;
	esac
	# check if we are in a build chroot
	if ! [  -f /etc/fstab -a ! -e /.buildenv -a -x "$DRACUT" ] ; then
		echo "Please run \"$DRACUT -f --regenerate-all\" as soon as your system is complete." >&2
		rm "$dir"/*
		exit 0
	fi
	break
done

err=0
work_done=

if test -e "$dir/all"; then
	rm "$dir"/*
	[ "$SKIP_REGENERATE_INITRD_ALL" = 1 ] || {
		"$DRACUT" -f --regenerate-all
		work_done=yes
	}
else
	for f in "$dir"/*; do
		case $f in
			"$dir/*")
				[ -e "$f" ] || break;;
		esac
		rm -f "$f"
		kver=${f##*/}
		case "$kver" in
			vmlinuz-*|image-*|vmlinux-*|linux-*|bzImage-*|uImage-*|Image-*|zImage-*)
				kver=${kver#*-}
				;;
		esac
		[ -d /lib/modules/"$kver" ] || {
			echo $0: skipping invalid kernel version "$dir/$kver"
			continue
		}
		if ! "$DRACUT" -f --kver "$kver"; then
			err=$?
		else
			work_done=yes
		fi
	done
fi

# For XEN/grub2 configurations, make sure the updated initrds are copied
# to the EFI system partition. See /etc/grub.d/20_linux_xen.
# The test for xen*.gz is simplistic but should be correct here.
# 20_linux_xen will apply more sophisticated heuristics to detect XEN.
[ ! "$work_done" ] || [ ! -d /sys/firmware/efi ] || \
	[ ! -x /sbin/update-bootloader ] || \
	[ "$(echo /boot/xen*.gz)" = "/boot/xen*.gz" ] || \
	/sbin/update-bootloader --refresh

exit $err
