#!/bin/sh
# init-premount: fetch the DEK over PCIe and unlock the LUKS volume.
#
# This file is SOURCED by init — never call exit here; failure paths must stop
# the boot in the initramfs (fail-closed).
#
# It only acts when the kernel command line carries "dek=1", so a later kernel
# upgrade that rebuilds the stock initramfs stays inert.

# initramfs-tools runs this script with "prereqs" while BUILDING the initrd.
# Without this guard the gate below reads the build host's /proc/cmdline (which
# may itself carry dek=1) and the script fetches a DEK at build time — with the
# board off that ends in fail_closed's sleep loop and the build hangs forever
# (observed 2026-10-23). This exit is safe: the branch only runs at build time,
# where the script is executed rather than sourced.
case "$1" in
prereqs)
    exit 0
    ;;
esac

case " $(cat /proc/cmdline) " in
  *" dek=1 "*)
    ;;
  *)
    return 0
    ;;
esac

DEK_KEY=/run/dek.key
DEK_MAPPER=dek-root
DEK_DEVICE="${DEK_DEVICE:-/dev/ubuntu-vg/dek-test}"
DEK_TIMEOUT="${DEK_TIMEOUT:-60s}"

# fail_closed stops the boot unconditionally.
#
# panic() alone is not enough: when it cannot open a console it falls through
# and the caller keeps running (observed 2026-10-23 — the host booted normally
# with no DEK). The loop below is the real guarantee.
fail_closed() {
    echo "dek: FAIL-CLOSED: $*" > /dev/kmsg
    panic "DEK fail-closed: $*"
    while :; do
        sleep 3600
    done
}

echo "dek: fetching DEK over PCIe (timeout $DEK_TIMEOUT)" > /dev/kmsg

if ! /bin/dek-fetch -key-out "$DEK_KEY" -timeout "$DEK_TIMEOUT"; then
    fail_closed "DEK unavailable over PCIe"
fi

if ! /sbin/cryptsetup luksOpen "$DEK_DEVICE" "$DEK_MAPPER" --key-file "$DEK_KEY"; then
    rm -f "$DEK_KEY"
    fail_closed "luksOpen $DEK_DEVICE failed"
fi

rm -f "$DEK_KEY"
echo "dek: LUKS volume unlocked, key removed" > /dev/kmsg

mkdir -p /mnt/dek-test
if mount -o ro "/dev/mapper/$DEK_MAPPER" /mnt/dek-test; then
    echo "dek: test volume mounted at /mnt/dek-test" > /dev/kmsg
else
    echo "dek: WARNING: unlocked but mount failed" > /dev/kmsg
fi
