#!/usr/bin/env bash

if [ -z "$BUILDDIR" ]; then 
    echo "BUILDDIR is not defined"
    exit 1
fi

KEYDIR="${BUILDDIR}/keys"

if [ -d "${KEYDIR}" ]; then
    echo "${KEYDIR} directory already is exist"
    echo "Skipping generating keys"
    exit 1
fi

mkdir "${KEYDIR}"
cd "${KEYDIR}"

echo "Generating private/public keys in .key/.crt format for PK, KEK et db"

openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_PK/ \
        -keyout PK.key -out PK.crt -nodes -days 365

openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_KEK/ \
        -keyout KEK.key -out KEK.crt -nodes -days 365

openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db/ \
		-keyout db.key -out db.crt -nodes -days 365


echo "Generatic EFI signature list file with PK, KEK et db public key"

cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \
        PK.crt PK.esl;

cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \
        KEK.crt KEK.esl

cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \
        db.crt db.esl

echo "Generatic EFI AUTH file with PK, KEK et db public key"

sign-efi-sig-list -c PK.crt -k PK.key PK PK.esl PK.auth
sign-efi-sig-list -c PK.crt -k PK.key KEK KEK.esl KEK.auth
sign-efi-sig-list -c KEK.crt -k KEK.key db db.esl db.auth

echo "Generatic DER files with PK, KEK et db public key"

# der certificate are need for OVMF based firmware (virtual machine)
openssl x509 -in PK.crt -outform der -out PK.der
openssl x509 -in KEK.crt -outform der -out KEK.der
openssl x509 -in db.crt -outform der -out db.der
