#!/bin/bash

function usage {

    local ecode=${2:-0}

    [[ -n $1 ]] && echo -e "\n $1" >&2

cat >&2 << helpMessage

 usage: ${0//*\//} int [0-7] (screen brightness)

  This script provides an alternate method for setting the laptop LCD backlight brightness
  on Toshiba laptops as workaround for https://bugzilla.novell.com/show_bug.cgi?id=887629.
  It makes use of '/sys/class/backlight/acpi_video0/brightness' to set brightness level
  between 0-7 where min=0, max=7. Additional options --increase/--decrease incrementally
  increase/decrease the brightness by 1.

 Options:

    -h  |  --help     program help (this file)
    -c  |  --check    returns the current backlight brightness
    -d  | --decrease  decrease current backlight brightness by 1
    -i  | --increase  increase current backlight brightness by 1

helpMessage

    exit $ecode;
}


test -n "$1" || usage "error: insufficient input" 1

## process options based on first argument (all options are exclusive)
case "$1" in

    -h | --help     )
        usage
        ;;

    -c | --check    )
        echo -n "Current Brightness: "
        cat /sys/class/backlight/acpi_video0/brightness
        exit 0
        ;;

    -d | --decrease )
        bl=`</sys/class/backlight/acpi_video0/brightness`
        test "$bl" -gt 0 && {
            # echo "current backlight: $bl, decreasing to $((bl-1))"
            test "$UID" -eq 0 && \
                echo $((bl-1)) > /sys/class/backlight/acpi_video0/brightness || \
                sudo bash -c "echo $((bl-1)) > /sys/class/backlight/acpi_video0/brightness"
        }
        ;;

    -i | --increase )
        bl=`</sys/class/backlight/acpi_video0/brightness`
        test "$bl" -lt 7 && {
            # echo "current backlight: $bl, increasing to $((bl+1))"
            test "$UID" -eq 0 && \
                echo $((bl+1)) > /sys/class/backlight/acpi_video0/brightness || \
                sudo bash -c "echo $((bl+1)) > /sys/class/backlight/acpi_video0/brightness"
        }
        ;;

    [0-7]           )
        test "$UID" -eq 0 && \
            echo $1 > /sys/class/backlight/acpi_video0/brightness || \
            sudo bash -c "echo $1 > /sys/class/backlight/acpi_video0/brightness"
        ;;

    *               )
        usage "error invalid argument" 1
        ;;

esac

exit 0
