#!/bin/bash
# plasma-optimus-kwin-drm.sh
# Exported by plasma-optimus at session startup.
#
# When prime-select is set to "nvidia", kwin_wayland must be told which DRM
# devices to use via KWIN_DRM_DEVICES, otherwise it falls back to the
# integrated GPU regardless of the prime-select setting.
#
# Format: KWIN_DRM_DEVICES=/dev/dri/<nvidia_card>:/dev/dri/<integrated_card>
#
# This file is sourced (not executed) by startplasma-wayland before kwin
# is launched.  Use "return" rather than "exit" throughout.

# Only relevant on Wayland sessions
[ "${XDG_SESSION_TYPE}" = "wayland" ] || return 0

# Require prime-select
command -v prime-select >/dev/null 2>&1 || return 0

# Only activate in nvidia mode
_primeMode="$(prime-select query 2>/dev/null)"
[ "${_primeMode}" = "nvidia" ] || return 0

# Scan all DRI card nodes and identify them by PCI vendor ID
_nvidiaCard=""
_integratedCard=""

for _sysCard in /sys/class/drm/card[0-9]*; do
    [ -f "${_sysCard}/device/vendor" ] || continue
    _vendor="$(cat "${_sysCard}/device/vendor" 2>/dev/null)"
    _devCard="/dev/dri/$(basename "${_sysCard}")"
    [ -e "${_devCard}" ] || continue

    case "${_vendor}" in
        0x10de)           _nvidiaCard="${_devCard}"      ;;  # NVIDIA
        0x8086 | 0x1002)  _integratedCard="${_devCard}"  ;;  # Intel or AMD
    esac
done

# Set the variable only when both a discrete and an integrated card are found
if [ -n "${_nvidiaCard}" ] && [ -n "${_integratedCard}" ]; then
    export KWIN_DRM_DEVICES="${_nvidiaCard}:${_integratedCard}"
fi
