#!/usr/bin/env bash
# Script to regenerate initramfs images, e.g. on systemd updates
# May also be called from other packages or scripts
# Why it was developed:
# https://bugzilla.rosalinux.ru/show_bug.cgi?id=9516
# License: GPLv3
# Upstream at https://abf.io/import/systemd
# Authors:
# - Mikhail Novosyolov <m.novosyolov@rosalinux.ru>, 2019set -efu
if systemd-detect-virt --quiet --container && ! env | grep -q '^SKIP_GEN=' ; then
SKIP_GEN=1
fi
if [ -f /etc/systemd-initramfs-gen.conf ]; then
. /etc/systemd-initramfs-gen.conf
fi
DEBUG="${DEBUG:-0}"
NO_MSG="${NO_MSG:-0}"
SKIP_GEN="${SKIP_GEN:-0}"
MAX_KERNELS="${MAX_KERNELS:-5}"
GENERATOR="${GENERATOR:-dracut}"
if [ "$DEBUG" != 0 ]; then set -x; fi
if [ "$SKIP_GEN" = 1 ] ; then
# Note: we do have to regen initrd in chroot
# because chroots are often used in rescue purposes.
# But there is no need to spend time for this in containers
if [ "$NO_MSG" != 0 ]; then exit 0; fi
echo "Running in container; no need to (re)generate initramfs — it's not used in containers."
echo "To force (re)generating initramfs run:"
echo "# env SKIP_GEN=0 systemd-initramfs-gen"
echo "and/or add SKIP_GEN=0 to /etc/systemd-initramfs-gen.conf to make it permanent."
exit 0
fi
list_of_img="$(find /boot -name 'initrd-*' -or -name 'initrd.img-*' -or -name 'initramfs-*' -or -name 'initramfs.img-*' | sort -u | tac)"
num_of_img="$(echo "$list_of_img" | wc -l)"
if [ "$num_of_img" -gt "$MAX_KERNELS" ] && [ "$NO_MSG" != 0 ]; then
echo "Initramfs for more than $MAX_KERNELS found. That's too many and will take too long."
echo "Will regenerate initramfs only for $MAX_KERNELS latest kernels."
echo "You may set MAX_KERNELS= in /etc/systemd-initramfs-gen.conf if you don't like this and rerun systemd-initramfs-gen."
fi
count=0
while read -r line
do
count=$((count+1))
if [ "$count" -gt "$MAX_KERNELS" ]; then break; fi
kernel="$(echo "$line" | sed \
-e 's,^/boot/initrd-,,' \
-e 's,^/boot/initrd.img-,,' \
-e 's,^/boot/initramfs-,,' \
-e 's,^/boot/initramfs.img-,,' \
-e 's,\.img$,,' \
)"
if [ -z "$kernel" ]; then continue; fi
case "$GENERATOR" in
dracut )
( set -x
dracut --force "$line" "$kernel" || : )
;;
update-initramfs )
( set -x
update-initramfs -u -k "$kernel" || : )
;;
* )
echo "Unknown \$GENERATOR, set dracut or update-initramfs. Exiting."
exit 1
;;
esac
unset kernel
done < <(echo "$list_of_img")