#! /bin/sh
#
# backlight	This script saves the backlight brightness between reboots.
#		It is called from boot, halt and reboot scripts.
#
#	(C) 2011 Arne Zellentin <arne.zellentin@kernelconcepts.de>
#
#	License: GPL (see http://www.gnu.org/licenses/gpl.txt)


cd /sys/class/backlight || exit 0

. /etc/default/rcS

savedir=/var/lib/backlight
save="$savedir/brightnesses"
min_bright=2

case "$1" in
start)
	[ "$VERBOSE" != no ] && echo "Restoring backlight brightness..."
	for i in * ; do
		b=$( grep 'brightness=' < /proc/cmdline \
			| sed -e 's/.*brightness=\([0-9]*\).*/\1/' )
		if [ -z "$b" -a -f "$save" ] ; then
			b=$( grep "$i:" < "$save" | sed -e s/"^$i:"// )
			if [ ! -z "$b" -a "$b" -lt "$min_bright" ]; then
				b="$min_bright"
			fi
		fi
		if [ -z "$b" ] ; then
			continue
		fi
		echo "$b" > "$i/brightness"
	done
	;;
stop)
	[ "$VERBOSE" != no ] && echo "Saving backlight brightness..."
		mkdir -p "$savedir" || exit 1
		> "$save"
		for i in * ; do
			echo -n "$i:" >> "$save"
			cat "$i"/actual_brightness >> "$save"
		done
	;;
*)
	echo "Usage: backlight {start|stop}" >&2
	exit 1
	;;
esac

exit 0
