#!/bin/bash

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

KERNELS=()
for version in `find /usr/lib/modules -mindepth 1 -maxdepth 1 -type d -printf '%P\n' | sort -V` ; do
	if [ -f "/usr/lib/modules/${version}/modules.dep" ] && [ -f "/usr/lib/modules/${version}/modules.order" ] && [ -f "/usr/lib/modules/${version}/modules.builtin" ]; then
		KERNELS+=("$version")
	fi
done

if [ "${#KERNELS[@]}" = 0 ] ; then
	echo "No kernels found in the current system. Exiting." >&2
	exit 1
fi

if [ ! -e /etc/default/devena ] ; then
	echo "Installing devena-firstboot config file ..."
	install -Dvm644 etc/default/devena /etc/default/devena
fi

OUTPUT=$1
if [ -z "$OUTPUT" ] ; then
	OUTPUT=/boot/devena-firstboot.img
fi

CHOSEN="${KERNELS[-1]}"
echo "-- Building devena-firstboot enabled initrd image ..."
dracut \
	--add "devena-firstboot" \
	--no-hostonly \
	"$OUTPUT" \
	"$CHOSEN" || {
		echo "Failed to generate $OUTPUT." >&2
		exit 1
	}
