#!/bin/bash

if [ $# -lt 1 ] || [ $# -gt 2 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
  cat << EOF
Usage: $0 PAYG_IMAGE [STORAGE_DIRECTORY]

  PAYG_IMAGE          An OS image in .gz or .qcow2 format
  STORAGE_DIRECTORY   Location to store the virtual machine files; if not
                      specified, these will be stored in the same directory as
                      PAYG_IMAGE

Create a virtual machine using GNOME Boxes, configured to use secure boot with
the Endless PAYG CA.

If PAYG_IMAGE is already in qcow2 format, it will be used directly. Otherwise,
it will be converted to a qcow2 file, stored in STORAGE_DIRECTORY.
EOF
  exit 1
fi

flatpak info org.gnome.Boxes &> /dev/null
if [ $? -eq 1 ] ; then
  echo "Please install GNOME Boxes Flatpak."
  exit 2
fi

# From here on out, all errors are fatal, and the user can clean up
set -e

if [ $# -eq 1 ] ; then
  destdir=$(dirname "$(realpath "$1")")
else
  destdir=$(realpath "$2")
  mkdir -p "$destdir"
fi

case "$1" in
  *.gz)
    echo Decompressing image file
    gunzip -dc "$1" > "${destdir}"/demo_image.raw

    echo Converting image to qcow2 format
    qcow2_path="${destdir}"/demo_image.qcow2
    flatpak run --command=qemu-img org.gnome.Boxes convert -f raw -O qcow2 "${destdir}"/demo_image.raw "$qcow2_path"
    rm -- "${destdir}"/demo_image.raw
    flatpak run --command=qemu-img org.gnome.Boxes resize "$qcow2_path" +8G
    ;;

  *.qcow2)
    qcow2_path="$(realpath "$1")"
    ;;

  *)
    echo Unsupported image format
    exit 3
    ;;
esac

# Copy the boot firmware and the pre-provisioned PAYG EFI variables
cp "/usr/share/eos-payg"/OVMF_CODE.secboot.fd "${destdir}/OVMF_CODE.secboot.fd"
cp "/usr/share/eos-payg"/OVMF_VARS_PAYG_demo.fd "${destdir}/OVMF_VARS_PAYG_demo.fd"

echo Registering VM
vm_uuid=$(cat /proc/sys/kernel/random/uuid)
sed -e s\\%FIRMWARE%\\"${destdir}/OVMF_CODE.secboot.fd"\\g \
    -e s\\%EFIVARS%\\"${destdir}/OVMF_VARS_PAYG_demo.fd"\\g \
    -e s\\%IMAGE%\\"${qcow2_path}"\\g \
    -e s\\%UUID%\\"${vm_uuid}"\\g \
    "/usr/share/eos-payg"/payg_vm.xml \
| flatpak run --command=virsh org.gnome.Boxes define /dev/stdin

echo Successfully installed PAYG demo VM
