#!/bin/sh

test -f /usr/share/acpi-support/power-funcs || exit 0

. /usr/share/acpi-support/power-funcs
. /usr/share/acpi-support/policy-funcs
. /etc/default/acpi-support

if [ -x /etc/acpi/local/lid.sh.pre ] ; then
	/etc/acpi/local/lid.sh.pre || exit
fi

if [ `CheckPolicy` = 0 ]; then exit; fi

grep -q closed /proc/acpi/button/lid/*/state
if [ $? = 0 ]
then
    for x in /tmp/.X11-unix/*; do
	displaynum=`echo $x | sed s#/tmp/.X11-unix/X##`
	getXuser;
	if [ x"$XAUTHORITY" != x"" ]; then
	    export DISPLAY=":$displaynum"	    
	    #. /usr/share/acpi-support/screenblank
	    if pidof xscreensaver > /dev/null; then
	       su $user -c "xscreensaver-command --lock"
	    fi
	fi
    done
    s2ram
else
    if [ x$RADEON_LIGHT = xtrue ]; then
	[ -x /usr/sbin/radeontool ] && radeontool light on
    fi
    for x in /tmp/.X11-unix/*; do
	displaynum=`echo $x | sed s#/tmp/.X11-unix/X##`
	getXuser;
	if [ x"$XAUTHORITY" != x"" ]; then
	    export DISPLAY=":$displaynum"
	    grep -q off-line /proc/acpi/ac_adapter/*/state
	    if [ $? = 1 ]
		then
		if pidof xscreensaver > /dev/null; then 
		    su $user -c "xscreensaver-command -unthrottle"
		fi
	    fi
	    if [ `pidof xscreensaver` ]; then
		su $user -c "xscreensaver-command -deactivate"
	    fi
	    su $user -c "xset dpms force on"
	    
	    # Press LEFT SHIFT. On some laptops / in some configurations forcing
	    # the DPMS on is not enough, X needs to be convinced to unblank the
	    # screen. The left shift key is probably the most harmless key we
	    # could press. :-)
	    acpi_fakekey 42
	fi
    done
fi
[ -x /etc/acpi/local/lid.sh.post ] && /etc/acpi/local/lid.sh.post
