#!/bin/sh

# sqp_JogglerBacklight.sh v1.07 (19th March 2012) by Andy Davison
#  Automatic backlight control with fading for the Joggler, tweaked for use by SqueezePlay.

PLATFORM=`cat /tmp/sqp_platform`
[ "$PLATFORM" = "native" ] || export PATH=$PATH:`dirname $0`

# Feed this ($1) Preferred Backlight ($2) Debug
setbl() {
	
	getbl
	PREFBL="$1"
	
	if [ $PREFBL -gt $CRNTBL ]; then
		STEP="1"
		STEPMSG="Brightening backlight..."
	elif [ $PREFBL -lt $CRNTBL ]; then
		STEP="-1"
		STEPMSG="Dimming backlight..."
	else
		STEP="0"
		STEPMSG="No action: backlight already at this value."
	fi

	if [ "$2" = "debug" ]; then
		echo "Using interface: $BLIF"
		echo "Current backlight level: $CRNTBL"
		echo "Set backlight level to:  $1"
		echo "$STEPMSG"
	fi

	if [ $STEP -eq 0 ]; then
		return
	fi

	for b in `seq $CRNTBL $STEP $PREFBL`;
	do

		if [ "$NATIVE" -lt 1 ]; then
			b=$(($b/3))
		fi
		
		[ "$2" != "debug" ] || echo $b

		echo "$b" > $BLIF
		$SLEEP

	done
	
}

getbl() {
	
	CRNTBL=`cat $BLIF`
	if [ "$NATIVE" -lt "1" ]; then
		CRNTBL=$(($CRNTBL*3))
	fi
	
}


## Check what system we're running on and whether we can access the backlight.
if [ -e /sys/class/backlight/openframe-bl/brightness ]; then
	BLIF="/sys/class/backlight/openframe-bl/brightness"
	NATIVE="0"
	SLEEP="sleep 0.001"
	if [ ! -w /sys/class/backlight/openframe-bl/brightness ]; then
		echo "Permissions do not currently allow you to set the backlight level."
		echo "Make sure that the udev rule is in place in /etc/udev/rules.d/"
	fi
elif [ -e /proc/blctrl ]; then
	BLIF="/proc/blctrl"
	NATIVE="1"
	SLEEP="usleep 3000"
else
	echo "No known backlight interface found."
	exit 0
fi


## Kill any other running instances first.
if [ "$1" != "888" ]; then
	if [ $NATIVE -lt "1" ]; then
		SQPBLPIDS=`ps aux | grep -v grep | grep -v $$ | grep $0 | awk -F\  '{print $2}'`
		kill `echo $SQPBLPIDS` 2>/dev/null
	else
		SQPBLPIDS=`ps | grep -v grep | grep -v $$ | grep $0 | awk -F\  '{print $1}'`
		kill `echo $SQPBLPIDS` 2>/dev/null
	fi
fi


## Give basic usage info or set the requested brightness.
if [ "$1" = "-h" ]; then
	echo "Usage: $0 [0-100] | [999]"
	echo "Enter either a backlight value between 0-100 or '999' to engage automatic backlight."
	exit 0
fi


## Then grab the current backlight value, adjusting if this is not the native OS.
getbl

if [ ! "$1" ]; then
	
	echo $CRNTBL

else
	
	## If we're in automatic mode, run a monitoring loop.
	if [ "$1" -eq "999" ]; then
		
		getbl
		LASTBL="$CRNTBL"
		
		while true
		do

			TIME=`date +%H`
			LIGHT=`readlightsensor`
			
			# Here we deal with 'night and day' variations.
			if [ "$TIME" -ge 22 ] || [ "$TIME" -lt 6 ]; then
				MODE="Night"
				# Night hysteresis values, so that less change is required to dim display, more is required to light it.
				HYSUP="-4"
				HYSDOWN="2"
			else
				MODE="Day"
				# Normal hysteresis values, so we don't 'bounce' the backlight with minor light changes.
				HYSUP="-3"
				HYSDOWN="3"
				# Artificially increase the read light level a bit.
				if [ ! "$LIGHT" -le "5" ]; then
					LIGHT=$(($LIGHT+10))
				fi
			fi
			
			PREFBL=$(($LIGHT))			
			DELTABL=$(($LASTBL-$PREFBL))
			
			if [ "$2" = "debug" 2>/dev/null ]; then
				echo "Current Mode is:       $MODE"
				echo "Light sensor reads:    $LIGHT"
				echo "Backlight % should be: $PREFBL"
				echo "Previous backlight % : $LASTBL"
				echo "Backlight delta %:     $DELTABL"
				echo
			fi
			
			if [ "$DELTABL" -le $HYSUP ] || [ "$DELTABL" -gt $HYSDOWN ]; then
				if [ "$2" = "debug" 2>/dev/null ]; then
					echo "Altering to: $PREFBL"
					echo
					setbl $PREFBL debug
				else
					setbl $PREFBL
				fi
				
			fi
						
			LASTBL="$PREFBL"
			sleep 2

		done
	
	## If we're given an '888', write out the current backlight 
	elif [ "$1" -eq "888" ]; then

		if [ "$NATIVE" -lt "1" ]; then
			echo `cat /sys/class/backlight/openframe-bl/brightness` > /tmp/sqp_initial_bl
		else
			echo `cat /proc/blctrl` > /tmp/sqp_initial_bl
		fi
		
	else

		setbl $1 $2

	fi

fi
