#!/usr/bin/env bash

set -euo pipefail

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

command -v apt-get >/dev/null 2>&1 || die "this script requires an APT-based distribution."
command -v dpkg >/dev/null 2>&1 || die "dpkg 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

architecture="$(dpkg --print-architecture)"
[[ "$architecture" == "amd64" ]] || \
  die "Steam's i386 runtime setup requires an amd64 system; detected $architecture."

echo "Enabling i386 package support..."
"${sudo_cmd[@]}" dpkg --add-architecture i386
"${sudo_cmd[@]}" apt-get update

if apt-cache show steam-installer >/dev/null 2>&1; then
  steam_package="steam-installer"
elif apt-cache show steam >/dev/null 2>&1; then
  steam_package="steam"
else
  die "no Steam package is available. Enable Ubuntu multiverse or Debian contrib/non-free first."
fi

packages=("$steam_package")
optional_packages=(
  libgl1-mesa-dri:i386
  libvulkan1
  libvulkan1:i386
  mesa-vulkan-drivers
  mesa-vulkan-drivers:i386
  vulkan-tools
)
for package in "${optional_packages[@]}"; do
  if apt-cache show "$package" >/dev/null 2>&1; then
    packages+=("$package")
  else
    echo "Warning: optional package is unavailable and will be skipped: $package" >&2
  fi
done

echo "Installing Steam and available graphics runtime packages..."
"${sudo_cmd[@]}" apt-get install -y "${packages[@]}"

echo
echo "Steam preparation completed."
echo "Install the vendor driver appropriate for your GPU, then run 'steam'."
