#!/bin/bash
#
# ac_dc_brightness
# remembers the brightness level for acadapter_online/offline
# not perfect and (hopefully) obsoleted by the powersaved brightness handling
# Stefan Seyfried 
#
. ${0%/*}/helper_functions # `dirname $0`/helper_functions
#
ARG="$1" # acadapter.online/acadapter.offline
STATEDIR=/var/lib
TOSHIBA=false

if [ -w /proc/acpi/asus ]; then
    # ASUS; asus_acpi module
    BRTFILE=/proc/acpi/asus/brn
elif [ -w /proc/acpi/sony/brightness ]; then
    # SONY; sony_acpi module
    BRTFILE=/proc/acpi/sony/brightness
elif [ -w /proc/acpi/toshiba/lcd ]; then
    # Toshiba; toshiba_acpi module; slightly more complicated
    BRTFILE=/proc/acpi/toshiba/lcd
    TOSHIBA=true
else
    $LOGGER "no ASUS, SONY or Toshiba ACPI module found. Can't do anything."
    $SCRIPT_RETURN $EV_ID 0 "ac_dc_brightness finished"
    EXIT 0
fi

case $ARG in
    acadapter.online)
	PREV=brightness.offline
	CURR=brightness.online
	;;
    acadapter.offline)
	PREV=brightness.online
	CURR=brightness.offline
	;;
    *)	# not called in an ac_online/offline event, figure it out by ourselves
	# this case is used e.g. for restoring after suspend, so we do not
	# store the current brightness.
	PREV=""
	if on_ac_power -q; then # online
	    CURR=brightness.online
	else # offline
	    CURR=brightness.offline
	fi
	;;
esac

if [ -n "$PREV" ]; then
    # BRTFILE exists, or we would not be here.
    if $TOSHIBA; then
	grep "^brightness:" $BRTFILE > $STATEDIR/$PREV
    else
	cat $BRTFILE > $STATEDIR/$PREV
    fi
fi
# if run for the first time, $CURR may not be here.
[ -f $STATEDIR/$CURR ] && cat $STATEDIR/$CURR > $BRTFILE

$SCRIPT_RETURN $EV_ID 0 "ac_dc_brightness finished"
EXIT 0
