#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# /usr/bin/pocketds-brightness {+|-}
#
# Step every backlight on the system up or down by 5% of its
# max_brightness. Called from pocketds-mode-listener when InputPlumber
# fires ui_brightness_up / ui_brightness_down (DBus signal mapped from
# the AYANEO Pocket DS top-edge rocker via
# /usr/share/inputplumber/profiles/pocketds-joymouse.yaml).
#
# v1: walks /sys/class/backlight/* and adjusts each. The Pocket DS has
# two backlights -- ae94000.dsi.0 (DSI-1, upper) and sy7758-backlight
# (DSI-2, lower) -- so both panels move together. A focused-screen
# variant (read KWin's cursorPos via DBus, find the output that
# contains it, write only that backlight) is a v2 -- requires
# session-bus access from this root-owned helper, which means either
# a small KWin Script or a runuser-into-the-active-user shim. Skipped
# for now.
#
# Step is 5% of max_brightness, clamped to [1, max] to avoid full-off.

set -e

case "${1:-}" in
    +)  sign=1 ;;
    -)  sign=-1 ;;
    *)  echo "usage: $0 {+|-}" >&2; exit 2 ;;
esac

for bl in /sys/class/backlight/*; do
    [ -d "$bl" ] || continue
    [ -r "$bl/max_brightness" ] || continue
    [ -w "$bl/brightness"     ] || continue

    max=$(cat "$bl/max_brightness")
    cur=$(cat "$bl/actual_brightness" 2>/dev/null || cat "$bl/brightness")
    step=$(( max / 20 ))                # 5%
    [ "$step" -lt 1 ] && step=1

    new=$(( cur + sign * step ))
    [ "$new" -lt 1    ] && new=1        # never fully off
    [ "$new" -gt "$max" ] && new=$max

    echo "$new" > "$bl/brightness" 2>/dev/null || :
done
