#!/bin/sh
# Filename:      ${GRML_FAI_CONFIG}/scripts/GRMLBASE/80-initramfs
# Purpose:       configure initramfs and rebuild it
# Authors:       grml-team (grml.org)
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2 or any later version.
################################################################################

set -u
set -e

# FAI sets $target, but shellcheck does not know that.
target=${target:?}

fcopy -M -v /etc/initramfs-tools/conf.d/xz-compress

fcopy -m root,root,0755 -v /usr/share/initramfs-tools/hooks/virtio-gpu

if ! [ -f "$target"/usr/share/initramfs-tools/scripts/live ] ; then
  echo "Error: live-boot/-initramfs does not seem to be present, can not create initramfs. Exiting.">&2
  exit 1
fi

echo "Rebuilding initramfs"

# Undo divert done in instsoft.
if [ '/usr/sbin/update-initramfs' != "$($ROOTCMD dpkg-divert --truename '/usr/sbin/update-initramfs')" ]; then
  echo "Undoing dpkg-divert of update-initramfs executable"
  $ROOTCMD rm -f /usr/sbin/update-initramfs
  $ROOTCMD dpkg-divert --rename --remove /usr/sbin/update-initramfs
fi

for initrd in $(basename "$target"/boot/vmlinuz-*) ; do
    if ! $ROOTCMD update-initramfs -k "${initrd##vmlinuz-}" -c ; then
        echo "Creating fresh initramfs did not work, trying update instead:"
        $ROOTCMD update-initramfs -k "${initrd##vmlinuz-}" -u
    fi
done

$ROOTCMD find /boot/ -name initrd\*.bak -exec rm {} \;
