#!/bin/bash

button=$2

lid_open() {
file=/proc/acpi/button/lid/$button/state
[ ! -f $file ] && return 0
grep -q open < $file && return 0
return 1
}

# Screen power on all active local X servers, arg 1 must be 'on' or 'off'
screen_power () {

local lock pid user disp xauth

if [ "$1" != "on" -a "$1" != "off" ] ; then
	echo "ERROR: invalid arg for screen_blanking()" 1>&2
	return 1
fi

/usr/local/sbin/radeontool light $1

# Throttle xscreensaver on each locally running X server
for lock in /tmp/.X*-lock ; do
	[ -O $lock ] || continue # effective ID is always root here
	pid=`cat $lock`
	pid=`echo $pid` # remove leading spaces
	tr '\0' '\n' < /proc/$pid/cmdline | egrep -q '(^|/)X$' || continue;
	user=`tr '\0' '\n' < /proc/$pid/environ | sed '/^USER=/{s/.*=//;p};d'`
	disp=`tr '\0' '\n' < /proc/$pid/cmdline | grep '^:[0-9][0-9]*$'`
	xauth=`tr '\0' '\n' < /proc/$pid/environ | sed '/^XAUTHORITY=/{s/.*=//;p};d'`
	[ -z "$disp" ] && continue
	[ -n "$xauth" ] && export XAUTHORITY=$xauth
	export DISPLAY=$disp
	[ $1 = on ] && xcmd=-unthrottle || xcmd=-throttle
	if [ -n "$user" -a "$user" != "root" ]; then
		su -c "xscreensaver-command $xcmd" $user
	else
		xscreensaver-command $xcmd
	fi
done
}

#date > /tmp/lid
if ! lid_open; then
	#echo "Turning off screen" >> /tmp/lid
	screen_power off
else
	#echo "Turning on screen" >> /tmp/lid
	screen_power on
fi
