#!/bin/bash
set -e
shopt -s extglob nullglob

set_brightness() {
    MAX="$(cat "$1"/max_brightness)"
    FILE="$1"/brightness
    VAL="$(($2 * MAX / 100 + 1))"

    [ "$VAL" -lt 0 ] && VAL=0
    [ "$VAL" -gt "$MAX" ] && VAL="$MAX"
    echo "$VAL" > "$FILE"
}

CUR_FILE=/var/tmp/current_brightness

set +e
CUR="$(cat "$CUR_FILE" || echo 50)"
set -e

CUR="$((CUR - CUR % "$1"))"

case "${1:0:1}" in
    '')
        exit 1
        ;;
    '+'|'-')
        NEW="$((CUR + "$1"))"
        ;;
    *)
        NEW="$1"
        ;;
esac

[ "$NEW" -lt 0 ] && NEW=0
[ "$NEW" -gt 100 ] && NEW=100

for dev in /sys/class/backlight/*; do
    set_brightness "$dev" "$NEW"
done

echo "$NEW" > "$CUR_FILE"
echo "$NEW"
