#!/bin/bash
set -e -o pipefail
. /etc/functions.sh

# Update initrd with CBFS files
if [ -z "$CONFIG_PCR" ]; then
	CONFIG_PCR=7
fi

CONFIG_GUID="74696e69-6472-632e-7069-6f2f75736572"

# copy EFI file named $CONFIG_GUID to /tmp, measure and extract
GUID=`uefi -l | grep "^$CONFIG_GUID"`

if [ -n "$GUID" ]; then
	STATUS "Loading $GUID from ROM"
	TMPFILE=/tmp/uefi.$$
	uefi -r $GUID | gunzip -c > $TMPFILE \
	|| DIE "Failed to read config GUID from ROM"

	if [ "$CONFIG_TPM" = "y" ]; then
		INFO "TPM: Extending PCR[$CONFIG_PCR] with content of $TMPFILE (UEFI configuration)"
		tpmr.sh extend -ix "$CONFIG_PCR" -if $TMPFILE \
		|| DIE "$GUID: tpm extend failed"
	fi

	STATUS "Extracting UEFI configuration"
	( cd / ; cpio -iud < $TMPFILE 2>/dev/null ) \
	|| DIE "Failed to extract config GUID"
	STATUS_OK "UEFI configuration loaded"
fi
