#!/bin/bash
# This script installs KVM, Virt-Manager, and sets up necessary configurations on Debian.
# It checks for doas or sudo for privilege escalation, installs required packages,
# enables and starts necessary services, and configures user permissions.

# Check for privilege escalation tool
[ -x "$(command -v doas)" ] && [ -e /etc/doas.conf ] && ld="doas"
[ -x "$(command -v sudo)" ] && ld="sudo"

# Exit if neither doas nor sudo is found
if [ -z "$ld" ]; then
  echo "Neither doas nor sudo is installed. Exiting."
  exit 1
fi

# Update package list
$ld apt update

# Install virt-manager, kvm and dependencies
$ld apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virtinst virt-manager -yy

# Optionally install ssh-askpass for graphical sudo prompt, useful when using X11 forwarding
$ld apt install ssh-askpass -yy

# Verify KVM installation (optional step for troubleshooting)
# kvm-ok

# Enable and start the libvirt daemon
$ld systemctl enable --now libvirtd

# Add current user to libvirt and libvirt-qemu groups for permissions
user="$(id -un)"
$ld adduser $user libvirt
$ld adduser $user libvirt-qemu

# Configure X11 Forwarding (ensure sshd_config on server has X11Forwarding yes)

echo "Installation and basic configuration complete."
echo "Remember to configure your SSH client and server for X11 forwarding."
