#!/usr/bin/env bash
set -euo pipefail
dev() { brightnessctl --list 2>/dev/null | awk '/kbd_backlight/ {print $2; exit}'; }
get_vals() {
  d="$(dev)"; [ -z "$d" ] && return 1
  cur="$(brightnessctl -d "$d" get)"; max="$(brightnessctl -d "$d" max)"
  echo "$d;$cur;$max"
}
print() {
  if vals="$(get_vals)"; then
    IFS=';' read -r d cur max <<<"$vals"
    [ "$max" -gt 0 ] || max=1
    pct=$(( cur * 100 / max ))
    # show in steps if small range
    steps=$(( max>10 ? 10 : max ))
    step=$(( cur * steps / max ))
    echo "{\"text\":\"⌨ ${pct}%\",\"class\":\"kbd $step/$steps\",\"tooltip\":\"Keyboard backlight: ${cur}/${max} (${pct}%)\\nScroll to adjust\"}"
  else
    echo '{"text":"⌨","class":"kbd none","tooltip":"No keyboard backlight device found"}'
  fi
}
case "${1:---print}" in
  --inc) if vals="$(get_vals)"; then IFS=';' read -r d cur max <<<"$vals"; brightnessctl -d "$d" set +1 >/dev/null; fi ;;
  --dec) if vals="$(get_vals)"; then IFS=';' read -r d cur max <<<"$vals"; brightnessctl -d "$d" set 1- >/dev/null; fi ;;
  --print) : ;;
  *) echo "Usage: $0 [--inc|--dec|--print]"; exit 1 ;;
esac
print

