#!/bin/bash
set -euo pipefail

OVMFDIR=/usr/share/ovmf
OVMF_CODE=${OVMFDIR}/x64/OVMF_CODE.fd
OVMF_VARS=${OVMFDIR}/x64/OVMF_VARS.fd
IPXE_IMAGE=/usr/share/ipxe-netboot/ipxe.efi

if [[ ! -f ${OVMF_CODE} ]]; then
  echo "ERROR: ${OVMF_CODE} is missing, install the ovmf package." >&2
  exit 1
fi
if [[ ! -f ${OVMF_VARS} ]]; then
  echo "ERROR: ${OVMF_VARS} is missing, install the ovmf package." >&2
  exit 1
fi
if [[ ! -f ${IPXE_IMAGE} ]]; then
  echo "ERROR: ${IPXE_IMAGE} is missing." >&2
  exit 1
fi

WORKDIR=$(mktemp -d --tmpdir netboot.XXXXXX)
cd "${WORKDIR}"

cp "${OVMF_VARS}" efivars
mkdir -p ./fat/EFI/Boot/
cp "${IPXE_IMAGE}" ./fat/EFI/Boot/bootx64.efi

exec qemu-system-x86_64 \
  -enable-kvm \
  -device virtio-net-pci,netdev=n -netdev user,ipv4,id=n \
  -m 2G \
  -drive if=pflash,format=raw,readonly,file="${OVMF_CODE}" \
  -drive if=pflash,format=raw,file=efivars \
  -usb -usbdevice disk:format=raw:fat:./fat \
  "$@"
