#!/bin/bash

# omarchy:summary=Print the most likely display backlight device.
# omarchy:examples=omarchy-hw-display

backlight_path="${OMARCHY_BACKLIGHT_PATH:-/sys/class/backlight}"

# The platform package may name backlights to skip and to prefer (see
# docs/file-layout.md).
displays_conf=/usr/share/omarchy-platform/displays.conf
skips=()
prefers=()
if [[ -r $displays_conf ]]; then
  # \r in IFS: a file saved with CRLF line ends reads the same.
  while IFS=$' \t\r' read -r directive argument extra || [[ -n $directive ]]; do
    [[ -n $argument && -z $extra && $argument != */* && $argument != . && $argument != .. ]] || continue
    case $directive in
    backlight-skip) skips+=("$argument") ;;
    backlight-prefer) prefers+=("$argument") ;;
    esac
  done <"$displays_conf"
fi

usable() {
  local skip
  # The Touch Bar on T2 Macs registers a backlight that never drives the display panel.
  [[ -n $1 && $1 != appletb_backlight ]] || return 1
  for skip in "${skips[@]}"; do
    # shellcheck disable=SC2053 # a skip is a glob
    [[ $1 == $skip ]] && return 1
  done
  return 0
}

# Start with the first possible output, then refine to the most likely given an order heuristic.
device=""
while IFS= read -r name; do
  if usable "$name"; then
    device="$name"
    break
  fi
done < <(ls -1 "$backlight_path" 2>/dev/null)

# gmux comes first: apple-gmux only registers when the kernel has already picked it, and on
# dual-GPU Macs the GPU's own PWM stops driving the panel once that GPU suspends. The
# platform's preferred backlights follow, then the GPU and ACPI ones.
# Glob the candidates in the loop list: [[ ]] does not do pathname expansion.
for candidate in "$backlight_path"/gmux_backlight "${prefers[@]/#/$backlight_path/}" "$backlight_path"/amdgpu_bl* "$backlight_path"/intel_backlight "$backlight_path"/acpi_video*; do
  if [[ -e $candidate ]] && usable "${candidate##*/}"; then
    device="${candidate##*/}"
    break
  fi
done

if [[ -n $device ]]; then
  printf '%s\n' "$device"
else
  exit 1
fi
