#!/bin/bash
# Generate a sealed UKI with embedded composefs digest
set -xeuo pipefail

# Path to the desired root filesystem
target=$1
shift
# Write to this directory
output=$1
shift
# Path to secrets directory
secrets=$1
shift

# Find the kernel version (needed for output filename)
kver=$(bootc container inspect --rootfs "${target}" --json | jq -r '.kernel.version')
if [ -z "$kver" ] || [ "$kver" = "null" ]; then
  echo "Error: No kernel found" >&2
  exit 1
fi

mkdir -p "${output}"

# Baseline ukify options
ukifyargs=(--measure
           --json pretty
           --output "${output}/${kver}.efi")

# Signing options, we use sbsign by default
ukifyargs+=(--signtool sbsign
            --secureboot-private-key "${secrets}/secureboot_key"
            --secureboot-certificate "${secrets}/secureboot_cert")

# Baseline container ukify options
containerukifyargs=(--rootfs "${target}")

# WORKAROUND: SELinux must be permissive for sealed UKI boot
# See https://github.com/bootc-dev/bootc/issues/1826
containerukifyargs+=(--karg enforcing=0)

# Build the UKI using bootc container ukify
# This computes the composefs digest, reads kargs from kargs.d, and invokes ukify
bootc container ukify "${containerukifyargs[@]}" -- "${ukifyargs[@]}"
