#!/bin/sh
set -eux

BRIGHTNESS_DIFF="$1"

# base dir for backlight class
BASEDIR='/sys/class/backlight/'

# get the backlight handler
HANDLER="$BASEDIR$(ls "$BASEDIR")"

# get current brightness
OLD_BRIGHTNESS="$(cat "$HANDLER/brightness")"

# get max brightness
MAX_BRIGHTNESS="$(cat "$HANDLER/max_brightness")"

# get current brightness %
OLD_BRIGHTNESS_P=$(( 100 * "$OLD_BRIGHTNESS" / "$MAX_BRIGHTNESS" ))

# calculate new brightness %, bounded by 0 100 range
NEW_BRIGHTNESS_P=$(("$OLD_BRIGHTNESS_P" + "$BRIGHTNESS_DIFF"))
NEW_BRIGHTNESS_P=$(("$NEW_BRIGHTNESS_P" > 100 ? 100 : "$NEW_BRIGHTNESS_P"))
NEW_BRIGHTNESS_P=$(("$NEW_BRIGHTNESS_P" < 1 ? 1 : "$NEW_BRIGHTNESS_P"))

# calculate new brightness value
NEW_BRIGHTNESS=$(( "$MAX_BRIGHTNESS" * "$NEW_BRIGHTNESS_P" / 100 ))

# set the new brightness value
echo "$NEW_BRIGHTNESS" > "$HANDLER/brightness" || doas chmod 666 "$HANDLER/brightness"
