#!/bin/bash

_glxExeStr="$(command -v glxinfo)"
_primeExeStr="$(command -v prime-select)"
_nvsmiExeStr="$(command -v nvidia-smi)"
_statusStr=""

_isWayland=false
if [ -n "${WAYLAND_DISPLAY}" ] || [ "${XDG_SESSION_TYPE}" = "wayland" ]; then
  _isWayland=true
fi

# Get current prime-select mode
_primeMode=""
if [ -x "${_primeExeStr}" ]; then
  _primeMode="$("${_primeExeStr}" query 2>/dev/null)"
fi

_get_nvidia_gpu_name() {
  # Try nvidia-smi first
  if [ -x "${_nvsmiExeStr}" ]; then
    local _name
    _name="$(${_nvsmiExeStr} --query-gpu=name --format=csv,noheader 2>/dev/null | head -1)"
    if [ -n "${_name}" ]; then
      echo "${_name}"
      return 0
    fi
  fi
  # Try /proc/driver/nvidia
  if [ -d /proc/driver/nvidia/gpus ]; then
    local _gpu_dir
    for _gpu_dir in /proc/driver/nvidia/gpus/*/; do
      if [ -f "${_gpu_dir}information" ]; then
        local _name
        _name="$(grep 'Model:' "${_gpu_dir}information" 2>/dev/null | sed 's/^Model:[[:space:]]*//')"
        if [ -n "${_name}" ]; then
          echo "${_name}"
          return 0
        fi
      fi
    done
  fi
  return 1
}

if [ "${_isWayland}" = true ]; then
  # Under Wayland, glxinfo runs through XWayland and may report the wrong GPU.
  # Use prime-select mode + nvidia-smi/sysfs for accurate detection.
  case "${_primeMode}" in
    nvidia)
      _statusStr="$(_get_nvidia_gpu_name)" || _statusStr="NVIDIA GPU is in use."
      ;;
    intel)
      _statusStr="INTEL GPU is in use."
      ;;
    on-demand)
      _gpuName="$(_get_nvidia_gpu_name)"
      if [ -n "${_gpuName}" ]; then
        _statusStr="Hybrid Mode: ${_gpuName} available on-demand"
      else
        _statusStr="ON-DEMAND mode is active."
      fi
      ;;
    *)
      _statusStr="Unknown GPU is in use"
      ;;
  esac
else
  # X11: glxinfo is reliable
  if [ -x "${_glxExeStr}" ]; then
    _statusStr="$(
      ${_glxExeStr} \
      | grep 'OpenGL renderer string' \
      | awk -F ': ' '{print $2}'
    )"
  elif [ -x "${_primeExeStr}" ]; then
    _statusStr="$( "${_primeExeStr}" query | tr '[:lower:]' '[:upper:]' )"
    _statusStr="${_statusStr} GPU is in use."
  else
    _statusStr='Unknown GPU is in use'
  fi
fi

echo "${_statusStr}"

