#!/usr/bin/env bash

set -euo pipefail

die() {
  echo "Error: $*" >&2
  exit 1
}

[[ -r /etc/os-release ]] || die "cannot identify the operating system."
# shellcheck source=/dev/null
. /etc/os-release
if [[ "${ID:-}" != "ubuntu" && "${ID_LIKE:-}" != *ubuntu* ]]; then
  die "ubuntu-drivers is Ubuntu-specific; this script requires Ubuntu or an Ubuntu derivative."
fi

command -v apt-get >/dev/null 2>&1 || die "apt-get is required."
if ((EUID == 0)); then
  sudo_cmd=()
elif command -v sudo >/dev/null 2>&1; then
  sudo_cmd=(sudo)
else
  die "run as root or install sudo."
fi

if command -v lspci >/dev/null 2>&1; then
  pci_devices="$(lspci -nn)"
  if ! grep -qi 'NVIDIA' <<<"$pci_devices"; then
    die "no NVIDIA PCI device was detected."
  fi
fi

echo "Installing Ubuntu's driver discovery utility..."
"${sudo_cmd[@]}" apt-get update
"${sudo_cmd[@]}" apt-get install -y ubuntu-drivers-common

echo "Available NVIDIA drivers:"
ubuntu-drivers list || true

echo "Installing Ubuntu's recommended NVIDIA driver..."
"${sudo_cmd[@]}" ubuntu-drivers install

echo "Installing NVIDIA settings and Vulkan diagnostics..."
"${sudo_cmd[@]}" apt-get install -y nvidia-settings vulkan-tools

echo
echo "NVIDIA driver installation completed. Reboot before using the new driver."
echo "After rebooting, verify it with 'nvidia-smi' and 'vulkaninfo --summary'."
