#!/bin/bash -e

all=0
lines=()
# Read the optional config file for automation
[[ -f /etc/bredos-dracut.conf ]] && source /etc/bredos-dracut.conf

while read -r line; do
	if [[ "${line}" != */vmlinuz ]]; then
		# triggers when it's a change to dracut files
		all=1
		continue
	fi

	lines+=("/${line%/vmlinuz}")

	pkgbase="$(<"${lines[-1]}/pkgbase")"
	install -Dm644 "/${line}" "/boot/vmlinuz-${pkgbase}"
done

if (( all )); then
	lines=(/usr/lib/modules/*)
fi

[[ ${DRACUT_QUIET} == "true" ]] && DRACUT_EXTRA_PARAMS=" --quiet"

for line in "${lines[@]}"; do
	if ! pacman -Qqo "${line}/pkgbase" &> /dev/null; then
		# if pkgbase does not belong to any package then skip this kernel
		continue
	fi

	pkgbase="$(<"${line}/pkgbase")"
	kver="${line##*/}"

	echo ":: Building initramfs for ${pkgbase} (${kver})"
	dracut --force --hostonly --no-hostonly-cmdline${DRACUT_EXTRA_PARAMS} /boot/initramfs-${pkgbase}.img "${kver}"

	if [[ ${NO_DRACUT_FALLBACK} != "true" ]]; then
		echo ":: Building fallback initramfs for ${pkgbase} (${kver})"
		dracut --force --no-hostonly${DRACUT_EXTRA_PARAMS} "/boot/initramfs-${pkgbase}-fallback.img" "${kver}"
	fi

	if [[ ${BUILD_UKI} == "true" ]]; then
		echo ":: Building UKI for ${pkgbase} (${kver})"
		dracut --hostonly --uefi${DRACUT_EXTRA_PARAMS} "/boot/EFI/bredos/${pkgbase}.efi" --kver "$kver" --force
	fi
done
