#!/usr/bin/env bash
#====================================================================
#  Proxmox VirtIO Drivers & Guest Tools Installer for Debian
#--------------------------------------------------------------------
#  Installs and configures VirtIO drivers, QEMU Guest Agent, and
#  ballooning support for Debian VMs running on Proxmox.
#====================================================================
set -euo pipefail

# === Colors ===
GREEN="\e[32m"; RED="\e[31m"; YELLOW="\e[33m"; RESET="\e[0m"

info()  { echo -e "${GREEN}➤ $1${RESET}"; }
warn()  { echo -e "${YELLOW}⚠️  $1${RESET}"; }
error() { echo -e "${RED}✖ $1${RESET}" >&2; exit 1; }

# === Root check ===
if [[ $EUID -ne 0 ]]; then
  error "This script must be run as root (use sudo)."
fi

# === VM environment detection ===
virt_type=$(systemd-detect-virt || echo "unknown")
dmi_product=$(cat /sys/class/dmi/id/product_name 2>/dev/null || echo "unknown")

if [[ "$virt_type" != "kvm" && "$virt_type" != "qemu" && "$dmi_product" != *"Proxmox"* ]]; then
  warn "This system does not appear to be running inside a Proxmox VM."
  warn "Detected virtualization: ${virt_type}, Product: ${dmi_product}"
  error "Aborting installation to avoid modifying a bare-metal or non-Proxmox system."
fi

info "✅ Verified: running in a Proxmox (QEMU/KVM) VM environment."

# === Update system ===
info "Updating package lists..."
apt update -y

# === Install base VirtIO and guest agent packages ===
info "Installing VirtIO drivers and Proxmox guest tools..."
apt install -y qemu-guest-agent spice-vdagent || error "Failed to install guest tools."

# === Optional kernel updates ===
info "Ensuring latest Debian kernel and headers..."
apt install -y linux-image-amd64 linux-headers-amd64

# === Enable QEMU guest agent ===
if systemctl list-unit-files | grep -q qemu-guest-agent; then
  info "Enabling and starting QEMU Guest Agent..."
  systemctl enable qemu-guest-agent
  systemctl start qemu-guest-agent
else
  warn "QEMU Guest Agent service not found — verify installation."
fi

# === Install ballooning support (optional) ===
if ! dpkg -l | grep -q balloonctl 2>/dev/null; then
  info "Installing memory ballooning support (if available)..."
  if apt install -y balloonctl 2>/dev/null; then
    info "Balloonctl installed successfully."
  else
    warn "Balloonctl not found in repositories — skipping."
  fi
else
  info "Balloonctl already installed."
fi

# === Load VirtIO kernel modules ===
info "Loading VirtIO modules..."
modprobe virtio_pci virtio_net virtio_blk virtio_balloon || warn "Some VirtIO modules could not be loaded."

# === Make VirtIO modules persistent ===
MODULES_FILE="/etc/modules"
declare -a MODULES=("virtio_pci" "virtio_net" "virtio_blk" "virtio_balloon")

for mod in "${MODULES[@]}"; do
  if ! grep -q "^$mod" "$MODULES_FILE"; then
    echo "$mod" >> "$MODULES_FILE"
    info "Added $mod to $MODULES_FILE"
  fi
done

# === Desktop integration ===
if systemctl get-default 2>/dev/null | grep -q "graphical"; then
  info "Detected GUI environment – installing SPICE agent..."
  apt install -y spice-vdagent
  systemctl enable spice-vdagent || true
else
  info "No graphical desktop detected – skipping SPICE integration."
fi

# === Show detected VirtIO devices ===
info "Detected VirtIO devices:"
lspci | grep -i virtio || warn "No VirtIO devices detected – check VM hardware config."

# === Verify loaded modules ===
info "Loaded VirtIO kernel modules:"
lsmod | grep virtio || warn "VirtIO modules not loaded – verify kernel support."

# === Final message ===
warn "Installation complete. Please reboot your VM to finalize setup."