#!/bin/sh
BACKLIGHT_BACKEND=${BACKLIGHT_BACKEND:-KERNEL}

kern () {
    for output in /sys/class/backlight/*; do
        backlight=$(cat $output/actual_brightness)
        max_backlight=$(cat $output/max_brightness)
        perc=$(expr $backlight \* 100 / $max_backlight)
        if [ -n "$1" ]; then
            if [ -n "$2" ]; then
                new_perc=$(expr $perc $1 $2)
            else
                new_perc=$1
            fi

            new_backlight=$(expr $new_perc \* $max_backlight / 100)
            [ $new_backlight -gt $max_backlight ] && new_backlight=$max_backlight
            [ $new_backlight -lt 0 ] && new_backlight=0
            echo $new_backlight > $output/brightness
        else
            echo $perc%
        fi
    done
}

xbl () {
    case "$1" in
        +)
            xbacklight -inc "$2"
            ;;
        -)
            xbacklight -dec "$2"
            ;;
        [0-9]*)
            xbacklight -set "$1"
            ;;
        *)
            xbacklight | sed 's/\.[0-9]*/%/'
            ;;
    esac
}

case "$BACKLIGHT_BACKEND" in
    KERNEL)
        kern $*
        ;;
    XBACKLIGHT)
        xbl $*
        ;;
esac

if [ -n "$1" ]; then
    pkill -SIGRTMIN+11 dwmblocks
fi
