#!/bin/bash

# omarchy:summary=Adjust keyboard backlight brightness using available steps.
# omarchy:args=[--no-osd] <up|down|cycle|off|restore>

no_osd=0
if [[ ${1:-} == "--no-osd" ]]; then
  no_osd=1
  shift
fi

direction="${1:-up}"

# Find keyboard backlight device (look for *kbd_backlight* pattern in leds class).
device=""
for candidate in /sys/class/leds/*kbd_backlight*; do
  if [[ -e $candidate ]]; then
    device="$(basename "$candidate")"
    break
  fi
done

if [[ -z $device ]]; then
  echo "No keyboard backlight device found" >&2
  exit 1
fi

# The level from before the first "off" since the last "restore", so the lock
# blanking again after a resume cannot save its own 0 over it.
saved="${XDG_RUNTIME_DIR:-/tmp}/omarchy-brightness-keyboard-$device"

if [[ $direction == "off" || $direction == "restore" ]]; then
  # The lock runs blank and wake as separate processes that can overlap.
  exec {lock_fd}>"$saved.lock" || exit 1
  flock "$lock_fd" || exit 1
fi

if [[ $direction == "off" ]]; then
  if [[ ! -s $saved ]]; then
    level="$(brightnessctl -d "$device" get)"
    if [[ $level =~ ^[0-9]+$ ]] && ! echo "$level" >"$saved"; then
      rm -f "$saved"
    fi
  fi
  # Never blank a level there is no record of to restore.
  [[ -s $saved ]] && brightnessctl -d "$device" set 0 >/dev/null
  exit 0
elif [[ $direction == "restore" ]]; then
  if [[ -f $saved ]]; then
    level="$(<"$saved")"
    if [[ ! $level =~ ^[0-9]+$ ]] || brightnessctl -d "$device" set "$level" >/dev/null; then
      rm -f "$saved"
    fi
  fi
  exit 0
fi

# Get current and max brightness to determine step size.
max_brightness="$(brightnessctl -d "$device" max)"
current_brightness="$(brightnessctl -d "$device" get)"

# Calculate step as 10% of max brightness. Keyboards with many levels (e.g. 512)
# need larger steps; keyboards with few levels (e.g. 3) fall back to step=1.
step=$(( max_brightness / 10 ))
(( step < 1 )) && step=1

if [[ $direction == "cycle" ]]; then
  new_brightness=$(( current_brightness + step ))
  (( new_brightness > max_brightness )) && new_brightness=0
elif [[ $direction == "up" ]]; then
  new_brightness=$(( current_brightness + step ))
  (( new_brightness > max_brightness )) && new_brightness=$max_brightness
else
  new_brightness=$(( current_brightness - step ))
  (( new_brightness < 0 )) && new_brightness=0
fi

# Set the new brightness.
brightnessctl -d "$device" set "$new_brightness" >/dev/null
(( no_osd )) || omarchy-osd -i keyboard -p "$(( new_brightness * 100 / max_brightness ))"
