#! /bin/sh
#
# Laptop mode tools module: control X display standby / suspend / off using DPMS
#


# getXuser gets the X user belonging to the display in $displaynum.
# (This code was borrowed from the Debian acpi-support package.)
getXuser() {
	user=`w -hs | awk '{ if ($3 == ":'$displaynum'" || $3 ~ /:'$displaynum'\..*/ || $2 == ":'$displaynum'" || $2 ~ /:'$displaynum'\..*/) { print $1; exit; } }'`
	if [ x"$user" = x"" ]; then
		startx=`pgrep -n startx`
		if [ x"$startx" != x"" ]; then
			user=`ps -o user --no-headers $startx`
		fi
	fi
	if [ x"$user" != x"" ]; then
        	userhome=`getent passwd $user | cut -d: -f6`
        	export XAUTHORITY=$userhome/.Xauthority
	else
		export XAUTHORITY=""
	fi
	export XUSER=$user
}


# Set X screen standby/suspend/powerdown timing
if [ x$CONTROL_DPMS_STANDBY = x1 ] ; then
	if [ $ON_AC -eq 1 ]; then
		if [ "$ACTIVATE" -eq 1 ]; then
			STANDBY="$LM_AC_DPMS_STANDBY"
			SUSPEND=$(($STANDBY+30))
			OFF=$(($STANDBY+60))
		else
			STANDBY="$NOLM_AC_DPMS_STANDBY"
			SUSPEND=$(($STANDBY+300))
			OFF=$(($STANDBY+600))
		fi
	else
		STANDBY="$BATT_DPMS_STANDBY"
		SUSPEND=$(($STANDBY+30))
		OFF=$(($STANDBY+60))
	fi

	# Loop through all X servers using their unix domain sockets.
	# (Partly borrowed from the Debian acpi-support package.)
	for x in /tmp/.X11-unix/*; do
		if [ -e "$x" ] ; then
			displaynum=`echo $x | sed -r 's#/tmp/.X11-unix/X([0-9]*)$#\1#'`
			$LM_VERBOSE && echo "Determining Xauthority for display $displaynum" >> $OUTPUT
			getXuser;
			if [ x"$XAUTHORITY" != x"" ]; then
				export DISPLAY=":$displaynum"	    
				if su $XUSER -c "xset dpms $STANDBY $SUSPEND $OFF" 2>> $OUTPUT | grep -q display >> $OUTPUT 2>&1 ; then
					$LM_VERBOSE && echo "Unable to set DPMS timeouts: X is not running on $DISPLAY" >> $OUTPUT
				else 
					$LM_VERBOSE && echo "Set screen $DISPLAY for the user $XUSER to standby in $STANDBY s, suspend in $SUSPEND s, powerdown in $OFF s using Xauthority $XAUTHORITY" >> $OUTPUT
				fi
			else
				$LM_VERBOSE && echo "Unable to determine Xauthority for display :$displaynum." >> $OUTPUT
			fi
		fi
	done
else
	$LM_VERBOSE && echo "CONTROL_DPMS_STANDBY is disabled, skipping..." >> $OUTPUT
fi
