#!/bin/bash

if [ "$EUID" -ne 0 ]; then
	echo "This script should be run as root."
	exit
fi

# Generate initrd using Dracut.
if [ -x /usr/bin/dracut ]; then
    for i in `ls /usr/lib/modules | grep -v 'extramodules'`; do
	if [ -f "/usr/lib/modules/${i}/modules.dep" ] && [ -f "/usr/lib/modules/${i}/modules.order" ] && [ -f "/usr/lib/modules/${i}/modules.builtin" ]; then
	        echo -e "\033[36m**\033[0m\tGenerating initrd (Initialization RAM Disk) for kernel version $i ..."
		dracut -q --force "/boot/initramfs-$i.img" "$i"
	else
		echo -e "\033[33m**\033[0m\tSkipping incomplete kernel modules tree $i ..."
	fi
    done
else
    echo -e "\033[33m**\033[0m\tCommand \"dracut\" is not installed, skipping generation.\n\tYou may not be able to boot the new kernel on the next boot."
fi

# Notify bootloader
if ! systemd-detect-virt -cq; then
    if [[ -x /usr/bin/grub-mkconfig ]]; then
	    echo -e "\033[36m**\033[0m\tUpdating GRUB for the new kernel..."
        grub-mkconfig -o /boot/grub/grub.cfg
    elif [[ -x /usr/bin/systemd-boot-friend && -r /etc/systemd-boot-friend.conf ]]; then
	    echo -e "\033[36m**\033[0m\tUpdating systemd-boot for the new kernel..."
        systemd-boot-friend install-kernel
    else
        true
    fi
fi

# TODO: Support for multiple other initramfs/initrd manager.
# TODO: Write in signal for PS1 to show "reboot" demand.
