#!/bin/bash

set -eu

if ! grep-dctrl -q -XFStatus "install ok installed" -a \
   -XFPackage initramfs-tools $1/var/lib/dpkg/status ; then
   exit 0
fi

# Install files

mkdir -p "$1/etc/initramfs-tools/conf.d/"
echo "RPI_BOOT_MEDIA=\"${IGconf_device_storage_type}\"" \
   > "$1/etc/initramfs-tools/conf.d/rpi-common"

sweep_initramfs_tools() {
   local layer=$1 version=$2 stempath=$3 _=$4 _=$5 _=$6 dest=$7
   local dir="${stempath}.d/device/initramfs-tools"
   [[ -d $dir ]] || return 0
   msg "initramfs-tools: installing for $layer $version"
   rsync --archive --verbose "${dir}/" "$dest"
}
foreach_layer_in_plan sweep_initramfs_tools "$1/etc/initramfs-tools/"

# Hint if the image layout has declared a rootfs type. This helps ensure
# the appropriate fsck binaries are installed.
if igconf isset image_rootfs_type ; then
   sed -i "s|FSTYPE=\([^ ]*\)|FSTYPE=${IGconf_image_rootfs_type}|" $1/etc/initramfs-tools/initramfs.conf
fi

# Create all images if kernel postinst was instructed to not generate, else
# update
if [ "${INITRD:-}" = "No" ]; then
   chroot $1 update-initramfs -c -k all
else
   chroot $1 update-initramfs -u -k all
fi
