#!/bin/bash
# Exit immediately on error, treat unset variables as errors, propagate pipe failures.
set -euo pipefail
# Load shared log/warn/skip helpers from the installer library.
source "$(dirname "${BASH_SOURCE[0]}")/../../lib/logging.sh"

log "Installing QEMU/KVM + libvirt stack + virt-manager..."
# qemu-full: full QEMU build with all emulation targets and utilities;
# libvirt: management daemon + API used by virt-manager; virt-manager: GUI front-end;
# virt-viewer: lightweight display client for VM consoles;
# dnsmasq: DHCP/DNS for the default NAT network; bridge-utils: bridge management;
# edk2-ovmf: UEFI firmware images for UEFI-boot VMs; swtpm: software TPM emulator;
# vde2: virtual distributed Ethernet for advanced networking topologies.
sudo pacman -S --noconfirm --needed \
    qemu-full \
    libvirt \
    virt-manager \
    virt-viewer \
    dnsmasq \
    bridge-utils \
    edk2-ovmf \
    swtpm \
    vde2

log "Enabling libvirtd service..."
# libvirtd must run as root to manage KVM devices and network namespaces.
enable_service libvirtd.service; start_service libvirtd.service

log "Configuring default NAT network for autostart..."
# The 'default' NAT network is created by libvirt on first start; net-autostart
# makes it come up automatically after each libvirtd restart.
# 2>/dev/null || true: suppress the error if the network does not yet exist
# (it will be created on first libvirtd run), preventing set -e from aborting.
sudo virsh net-autostart default 2>/dev/null || true

log "Adding $USER to libvirt and kvm groups..."
# Membership in libvirt allows managing VMs without sudo; kvm grants direct
# access to /dev/kvm for hardware acceleration.  Group changes only apply
# after the user logs out and back in.
sudo usermod -aG libvirt,kvm "$USER"
log "QEMU/KVM installed. Log out and back in for group membership to take effect."
