#!/bin/sh
set -eu

# Verify Secure Boot prerequisites
/usr/lib/puavo-ltsp-install/puavo-prepare-secure-boot

images_directory="/images"
addons_directory="${images_directory}/boot/addons"

db_auth="${addons_directory}/db.auth"
kek_auth="${addons_directory}/kek.auth"
pk_auth="${addons_directory}/pk.auth"

panic() {
  printf "%b\n" "error: $1" >&2
  exit 1
}

remove_immutability() {
  local f
  for f in "$@"; do
    test -f "$f" || continue
    chattr -i "$f" || return 1
  done
}

[ -f "$db_auth" ]  || panic "db.auth not found"
[ -f "$kek_auth" ] || panic "kek.auth not found"
[ -f "$pk_auth" ]  || panic "pk.auth not found"

echo "enrolling Secure Boot keys..."

# Remove immutability from Secure Boot variables to allow writing.
# They become immutable after each write.
remove_immutability /sys/firmware/efi/efivars/db-*  \
                    /sys/firmware/efi/efivars/KEK-* \
                    /sys/firmware/efi/efivars/PK-*

# No dbx is enrolled due to limited firmware variable storage.
# Setup Mode is reached by clearing the keys, which leaves it empty.
efi-updatevar -f "$db_auth" db || panic "failed to enroll db"
efi-updatevar -f "$kek_auth" KEK || panic "failed to enroll KEK"
# Writing PK exits Setup Mode and activates Secure Boot
efi-updatevar -f "$pk_auth" PK || panic "failed to enroll PK"

echo "Secure Boot configured successfully"
exit 0
