#!/bin/bash

# omarchy:summary=Detect whether the system has an active hybrid GPU configuration

# Count display controllers (PCI class 0x03) from the cached sysfs IDs rather
# than lspci, which reads PCI config space and resumes a runtime-suspended
# dGPU -- on every menu open, since the menu's Hybrid GPU row asks this.
pci_devices_path="${OMARCHY_PCI_DEVICES_PATH:-/sys/bus/pci/devices}"

multiple_gpus() {
  local device class count=0

  for device in "$pci_devices_path"/*; do
    [[ -r $device/class ]] && read -r class <"$device/class" && [[ $class == 0x03* ]] && ((count += 1))
  done

  ((count >= 2))
}

if omarchy-cmd-present supergfxctl; then
  # A wedged supergfxd blocks its clients forever, and this gate runs while
  # the menu renders. Bound the query, and treat a daemon that cannot answer
  # like a machine without supergfxctl: count GPUs instead of hiding hardware
  # that is really there.
  modes=$(timeout --kill-after=1s 1s supergfxctl -s 2>/dev/null)
  status=$?

  if ((status == 124 || status == 137)); then
    multiple_gpus
  else
    grep -qw Hybrid <<<"$modes"
  fi
else
  multiple_gpus
fi
