#!/bin/bash

# omarchy:summary=Install lib32 graphics drivers (Vulkan + NVIDIA) for any detected GPUs.
# omarchy:group=install
# omarchy:name=gaming gpu-lib32
# omarchy:requires-sudo=true

set -e

# lib32 drivers come from Arch's multilib repository, which only exists on
# x86_64. aarch64 runs Valve's native arm64 Steam client and needs none.
omarchy-hw-x86 || exit 0

# Armbian: the 32-bit libraries come from the i386 architecture.
if ! dpkg --print-foreign-architectures | grep -qx i386; then
  sudo dpkg --add-architecture i386
  sudo apt-get update
fi

echo "Installing lib32 graphics drivers..."

PACKAGES=()

declare -A VULKAN_DRIVERS=(
  [Intel]=lib32-vulkan-intel
  [AMD]=lib32-vulkan-radeon
)
for vendor in "${!VULKAN_DRIVERS[@]}"; do
  if lspci | grep -iE "(VGA|Display).*$vendor" >/dev/null; then
    PACKAGES+=("${VULKAN_DRIVERS[$vendor]}")
  fi
done

# Fall back to the installed NVIDIA driver package when supergfxd's Integrated
# mode has detached the dGPU from PCI. Check nvidia-580xx-utils before
# nvidia-utils because nvidia-580xx-utils provides nvidia-utils in pacman.
if omarchy-hw-nvidia-gsp; then
  PACKAGES+=(lib32-nvidia-utils nvidia-prime)
elif omarchy-hw-nvidia-without-gsp; then
  PACKAGES+=(lib32-nvidia-580xx-utils nvidia-prime)
elif omarchy-pkg-present nvidia-580xx-utils; then
  PACKAGES+=(lib32-nvidia-580xx-utils nvidia-prime)
elif omarchy-pkg-present nvidia-utils; then
  PACKAGES+=(lib32-nvidia-utils nvidia-prime)
fi

if (( ${#PACKAGES[@]} > 0 )); then
  omarchy-pkg-add "${PACKAGES[@]}"
fi

if grep -Eq '"mode"[[:space:]]*:[[:space:]]*"Integrated"' "${OMARCHY_SUPERGFXD_CONF:-/etc/supergfxd.conf}" 2>/dev/null && omarchy-hw-hybrid-gpu; then
  echo ""
  echo "$(omarchy-i18n gpu.integratedActive). $(omarchy-i18n gpu.switchToDgpuHint)"
fi
