#!/bin/bash

set -eux

cd "${0%/*}"

if [[ -d "secureboot" ]]; then
    echo "Running with Secure Boot enabled"

    # See: https://github.com/rhuefi/qemu-ovmf-secureboot
    # $ dnf install -y python3-virt-firmware
    if [[ ! -f "VARS_CUSTOM.secboot.fd.template" ]]; then
        GUID=$(cat secureboot/GUID.txt)
        virt-fw-vars --input "/usr/share/edk2/ovmf/OVMF_VARS.fd" \
            --secure-boot  \
            --set-pk  $GUID "secureboot/PK.crt" \
            --add-kek $GUID "secureboot/KEK.crt" \
            --add-db  $GUID "secureboot/db.crt" \
            -o "VARS_CUSTOM.secboot.fd.template"
    fi

    # Reset the firmware config to the default
    cp "VARS_CUSTOM.secboot.fd.template" "VARS_CUSTOM.secboot.fd"

    qemu_args=(
        '-cpu' 'host'
        '-machine' 'pc-q35-9.1,smm=on'
        '-global' 'driver=cfi.pflash01,property=secure,value=on'
        '-drive' 'if=pflash,format=raw,unit=0,readonly=on,file=/usr/share/edk2/ovmf/OVMF_CODE.secboot.fd'
        '-drive' 'if=pflash,format=raw,unit=1,file=./VARS_CUSTOM.secboot.fd'
    )
else
    echo "Not running with Secure Boot enabled"

    qemu_args=(
        '-bios' '/usr/share/edk2/ovmf/OVMF_CODE.fd'
    )
fi

qemu-system-x86_64 \
    -nographic \
    -m 4096 \
    -enable-kvm \
    -drive file=fedora-unified-secureboot-efi.qcow2,if=virtio,cache=unsafe \
    -nic user,model=virtio-net-pci \
    "${qemu_args[@]}"
