#!/bin/bash
# Download the CachyOS desktop ISO (with checksum verification), create a
# 64GB qcow2 disk, and define+boot the VM via virt-install, UEFI + virtio,
# bridged on br0. Leaves the VM booted to the graphical installer (Calamares)
# for interactive install via virt-viewer.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
source ./00-config.sh

sudo mkdir -p "$ISO_DIR"

if [ ! -f "$ISO_PATH" ]; then
    echo ">>> Downloading $ISO_NAME"
    sudo curl -L --fail --retry 3 -o "${ISO_PATH}.sha256" "${ISO_URL}.sha256"
    sudo curl -L --fail --retry 3 -o "$ISO_PATH" "$ISO_URL"
fi

echo ">>> Verifying checksum"
(cd "$ISO_DIR" && sudo sha256sum -c "${ISO_NAME}.sha256")

sudo virsh -c qemu:///system pool-refresh isos-1 2>/dev/null || true

if [ ! -f "$VM_DISK" ]; then
    echo ">>> Creating disk $VM_DISK"
    sudo qemu-img create -f qcow2 "$VM_DISK" "$VM_DISK_SIZE"
fi

echo ">>> Defining and starting VM $VM_NAME"
sudo virt-install \
    --name "$VM_NAME" \
    --memory "$VM_MEMORY_MB" \
    --vcpus "$VM_VCPUS" \
    --cpu host-passthrough \
    --disk "path=${VM_DISK},bus=virtio" \
    --cdrom "$ISO_PATH" \
    --network "network=${VM_NETWORK},model=virtio" \
    --boot uefi \
    --os-variant archlinux \
    --graphics spice \
    --video qxl \
    --channel spicevmc \
    --noautoconsole

echo ">>> VM started. Connect with: virt-viewer --connect qemu:///system $VM_NAME"
echo ">>> Complete the graphical Calamares install, then run 02-bootstrap-ssh-via-console.sh"
