#!/bin/bash

if [ -z "$KMS_KEY_TOKEN" ]; then
  KMS_KEY_TOKEN="PAYG-UEFI-2025"
fi
# Format: pkcs11:token=<KMS-Key-Label-or-ID>
KMS_KEY_URI="pkcs11:token=${KMS_KEY_TOKEN}"

# Handle options from rpi-eeprom-digest
# https://github.com/raspberrypi/rpi-eeprom/blob/v2026.05.11-2712/rpi-eeprom-digest#L116
while getopts "a:" opt; do
  case $opt in
    a) ALGO=$OPTARG ;;
    *) echo "Invalid option" >&2; exit 1 ;;
  esac
done
shift $((OPTIND-1))

INPUT_FILE="$1"
OUTPUT_BIN=$(mktemp)
trap 'rm -f "$OUTPUT_BIN"' EXIT

# Sign the target file using OpenSSL Engine with the AWS KMS PKCS#11 library by
# following how does rpi-eeprom-digest sign
# https://github.com/raspberrypi/rpi-eeprom/blob/v2026.05.11-2712/rpi-eeprom-digest#L118
openssl dgst -engine pkcs11 \
    -sign "$KMS_KEY_URI" \
    -keyform engine \
    -sha256 \
    -out "$OUTPUT_BIN" \
    "$INPUT_FILE"

# Convert binary signature directly to the raw hex string format expected by
# rpi-eeprom-digest
xxd -p -c 256 "$OUTPUT_BIN"
