#!/bin/sh
# Update the /boot partition signatures
set -o pipefail
. /etc/functions

XEN="$1"
KERNEL="$2"
INITRD="$3"
BOOT_HASHES="/boot/boot.hashes"

if [ -z "$XEN" -o -z "$KERNEL" -o -z "$INITRD" ]; then
	die "Usage: $0 /boot/xen... /boot/vmlinuz... /boot/initramfs..."
fi

# setup the USB so we can reach the GPG card
if ! lsmod | grep -q ehci_hcd; then
	insmod /lib/modules/ehci-hcd.ko \
	|| die "ehci_hcd: module load failed"
fi
if ! lsmod | grep -q ehci_pci; then
	insmod /lib/modules/ehci-pci.ko \
	|| die "ehci_pci: module load failed"
fi
if ! lsmod | grep -q xhci_hcd; then
	insmod /lib/modules/xhci-hcd.ko \
	|| die "ehci_hcd: module load failed"
fi
if ! lsmod | grep -q xhci_pci; then
	insmod /lib/modules/xhci-pci.ko \
	|| die "ehci_pci: module load failed"
	sleep 2
fi

gpg --card-status \
|| die "gpg card read failed"

# if the /boot.hashes file already exists, read the TPM counter ID
# from it.
if [ -r "$BOOT_HASHES" ]; then
	TPM_COUNTER=`grep counter- "$BOOT_HASHES" | cut -d- -f2`
else
	warn "$BOOT_HASHES does not exist; creating new TPM counter"
	read -s -p "TPM Owner password: " tpm_password
	echo
	tpm counter_create \
		-pwdo "$tpm_password" \
		-pwdc '' \
		-la 3135106223 \
	| tee /tmp/counter \
	|| die "Unable to create TPM counter"
	TPM_COUNTER=`cut -d: -f1 < /tmp/counter`
fi
	
if [ -z "$TPM_COUNTER" ]; then
	die "$BOOT_HASHES: TPM Counter not found?"
fi

mount -o rw,remount /boot \
|| die "Could not remount /boot"

tpm counter_increment -ix "$TPM_COUNTER" -pwdc '' \
	| tee /tmp/counter-$TPM_COUNTER \
|| die "Counter increment failed"

sha256sum \
	"$XEN" \
	"$KERNEL" \
	"$INITRD" \
	"/tmp/counter-$TPM_COUNTER" \
| tee "$BOOT_HASHES"

for tries in 1 2 3; do
	if gpg --detach-sign -a "$BOOT_HASHES"; then
		mount -o ro,remount /boot
		exit 0
	fi
done

warn "$BOOT_HASHES: Unable to sign boot hashes"
mount -o ro,remount /boot
exit 1
