#!/bin/bash
echo "[+] Generating..."
if [ -f PK-GUID ] && [ -f PK-vmpriv.key ] && [ -f PK-vm.crt ] && [ -f PK-vm.der ] && [ -f PK-vm.esl ] && [ -f PK-vm.auth ] &&
[ -f KEK-vmpriv.key ] && [ -f KEK-vm.crt ] && [ -f KEK-vm.der ] && [ -f KEK-vm.esl ] && [ -f KEK-vm.auth ] &&
[ -f db-vmpriv.key ] && [ -f db-vm.crt ] && [ -f db-vm.der ] && [ -f db-vm.esl ] && [ -f db-vm.auth ]; then
    echo "[*] Keys already generated as {PK,KEK,db}-vm{priv.key,.crt,.der,.esl,.auth}";
else
    rm -f "{PK,KEK,db}-vm{priv.key,.crt,.der,.esl,.auth}";
    rm -f PK-GUID;
    uuidgen --random > PK-GUID;
    openssl req -config uefi_pk-openssl.cnf -newkey rsa:2048 -nodes -keyout PK-vmpriv.key -x509 -days 36500 -out PK-vm.crt;
    openssl x509 -in PK-vm.crt -outform der -out PK-vm.der;
    cert-to-efi-sig-list -g "$(< PK-GUID)" PK-vm.crt PK-vm.esl;
    sign-efi-sig-list -g "$(< PK-GUID)" -k PK-vmpriv.key -c PK-vm.crt PK PK-vm.esl PK-vm.auth;
    openssl req -config uefi_kek-openssl.cnf -newkey rsa:2048 -nodes -keyout KEK-vmpriv.key -x509 -days 36500 -out KEK-vm.crt;
    openssl x509 -in KEK-vm.crt -outform der -out KEK-vm.der;
    cert-to-efi-sig-list -g "$(< PK-GUID)" KEK-vm.crt KEK-vm.esl;
    sign-efi-sig-list -g "$(< PK-GUID)" -k PK-vmpriv.key -c PK-vm.crt KEK KEK-vm.esl KEK-vm.auth;
    openssl req -config uefi_db-openssl.cnf -newkey rsa:2048 -nodes -keyout db-vmpriv.key -x509 -days 36500 -out db-vm.crt;
    openssl x509 -in db-vm.crt -outform der -out db-vm.der;
    cert-to-efi-sig-list -g "$(< PK-GUID)" db-vm.crt db-vm.esl;
    sign-efi-sig-list -g "$(< PK-GUID)" -k KEK-vmpriv.key -c KEK-vm.crt db db-vm.esl db-vm.auth;
    echo "[+] Completed key generation as {PK,KEK,db}-vm{priv.key,.crt,.der,.esl,.auth}";
fi
echo "[i] Sign via 'sbsign --key db-vmpriv.key --cert db-vm.crt --output <file 1> ... <file n>'";