#!/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
allow_missing_verity=$1
shift
seal_state=$1
shift

if [[ $seal_state == "sealed" && $allow_missing_verity == "true" ]]; then
    echo "Cannot have missing verity with sealed UKI" >&2
    exit 1
fi

# 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")

if [[ $seal_state == "sealed" ]]; then
    # Signing options, we use sbsign by default
    ukifyargs+=(--signtool sbsign
                --secureboot-private-key "${secrets}/secureboot_key"
                --secureboot-certificate "${secrets}/secureboot_cert")
fi

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

missing_verity=()

if [[ $allow_missing_verity == "true" ]]; then
    missing_verity+=(--allow-missing-verity)
fi

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