#!/usr/bin/env bash
# scripts/prereqs/install-virtualization.sh [--check|--dry-run]
#
# Prereq installer: libvirt + KVM/QEMU + virsh -- the virtualization substrate
# the vcloud host runs on (dc-dc Stage 1+: pools, networks, node VMs). Installs
# libvirt-daemon-system, qemu-kvm, libvirt-clients, virtinst, and adds the
# invoking user to the `libvirt` group. Debian/Ubuntu (apt). Idempotent.
#
#   --check     report virsh/qemu presence + qemu:///system reach + group; exit 0/1
#   --dry-run   print what it would do; mutate nothing
#   (no flag)   install missing packages + add user to libvirt group (sudo)
#
# NOTE: a freshly-added group membership needs a re-login (or `newgrp libvirt`)
# to take effect. Exit: 0 ok/installed | 1 check-failed | 2 bad args |
# 3 unsupported OS | 4 install failed. ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/lib-prereq.sh"
PKGS="libvirt-daemon-system qemu-kvm libvirt-clients virtinst"

pq_parse_mode "$@"; rc=$?
[ "$rc" = "10" ] && { echo "usage: bash scripts/prereqs/install-virtualization.sh [--check|--dry-run]"; exit 0; }
[ "$rc" = "0" ] || exit "$rc"

report() {
  local ok=0
  pq_have virsh && echo "OK: virsh present ($(virsh --version 2>/dev/null))" || { echo "ABSENT: virsh"; ok=1; }
  pq_have qemu-system-x86_64 && echo "OK: qemu-system-x86_64 present" || { echo "ABSENT: qemu-system-x86_64"; ok=1; }
  if pq_have virsh && virsh -c qemu:///system list --all >/dev/null 2>&1; then
    echo "OK: qemu:///system reachable"
  else
    echo "WARN: qemu:///system not reachable yet (daemon down, or group not active until re-login)"
  fi
  if id -nG 2>/dev/null | tr ' ' '\n' | grep -qx libvirt; then
    echo "OK: user in 'libvirt' group"
  else
    echo "ABSENT: user not in 'libvirt' group (re-login needed after install)"; ok=1
  fi
  return "$ok"
}

report; st=$?
[ "$PQ_CHECK" = "1" ] && exit "$st"
[ "$st" = "0" ] && { echo "-- all virtualization prereqs already satisfied --"; exit 0; }

pq_require_apt "libvirt/qemu" || exit 3
pq_run "apt-get update" -- sudo apt-get update || { echo "FAIL: apt-get update" >&2; exit 4; }
# shellcheck disable=SC2086
pq_run "install: $PKGS" -- sudo apt-get install -y $PKGS || { echo "FAIL: package install" >&2; exit 4; }
pq_run "add user '${USER:-$(id -un)}' to the libvirt group" -- sudo usermod -aG libvirt "${USER:-$(id -un)}" \
  || { echo "FAIL: usermod" >&2; exit 4; }

[ "$PQ_DRYRUN" = "1" ] && { echo "  (dry-run: no changes made)"; exit 0; }
echo "INSTALLED. NOTE: log out/in (or run 'newgrp libvirt') for the group to take effect, then re-run --check."
exit 0
