#!/bin/sh
#
# Kernel hook for m1n1, taken from update-m1n1 and efibootmgr.
#
# Arguments passed to this script: $1 pkgname, $2 version.

set -e

PKGNAME="$1"
VERSION="$2"

[ -e "${ROOTDIR}/etc/default/m1n1-kernel-hook" ] && . "${ROOTDIR}/etc/default/m1n1-kernel-hook"
[ -d "${BOOT}" ] || exit 0
[ -d "${M1N1_T}" ] || exit 0

m1n1config=/run/m1n1.conf
: >"$m1n1config"

if [ -e "$CONFIG" ]; then
	echo "Reading m1n1 config from $CONFIG:"
	while read line; do
		case "$line" in
			"") ;;
			\#*) ;;
			chosen.*=*|display=*|mitigations=*)
				echo "$line" >> "$m1n1config"
				echo "Option: $line"
				;;
			*)
				echo "Ignoring unknown option: $line"
				;;
		esac
	done <$CONFIG
fi

case "$PAYLOAD" in
	kernel)
		cat "${M1N1}" $m1n1config >"${TARGET}.new"
		cat ${DTBS} >>"${TARGET}.new"
		gzip -c "${BOOT}/initramfs-${VERSION}.img" >>"${TARGET}.new"
		gzip -c "${BOOT}/vmlinux-${VERSION}" >>"${TARGET}.new"
		echo "Payload: m1n1 config dtbs initramfs kernel"
	;;
	uboot)
		cat "${M1N1}" ${DTBS} >"${TARGET}.new"
		gzip -c "${U_BOOT}" >>"${TARGET}.new"
		cat $m1n1config >>"${TARGET}.new"
		echo "Payload: m1n1 dtbs uboot config"
	;;
	*)
		echo "Error: unknown PAYLOAD" && exit 1
	;;
esac

[ -e "$TARGET" ] && cp --preserve=timestamps "$TARGET" "${TARGET}.old"
mv -f "${TARGET}.new" "$TARGET"

echo "m1n1 updated at ${TARGET}"
