#!/bin/sh
#
#
# by Stefan Tomanek stefan@pico.ruhr.de
#
# Call this script from your acpi setup

LINE="$(who | egrep '^\w+[[:space:]]+:[[:digit:]]+[[:space:]]+')"
USER="$(echo $LINE | awk '{print $1}')"
DISPLAY="$(echo $LINE | awk '{print $2}')"
if grep "closed" /proc/acpi/button/lid/$2/state ; then
	if [ "$LINE" != ""  ]; then
		# Are we running xscreensaver?
		if pgrep -U $USER -x xscreensaver; then
		    # Disable all graphical savers and lock display
		    su $USER -c "xscreensaver-command -display $DISPLAY -throttle"
		    su $USER -c "xscreensaver-command -display $DISPLAY -lock"
		else
		    # We are not running xscreensaver, we'll use xlock
		    
		    # if we only have battery power, just blank the
		    # screen to save energy
		    MODE="-mode blank"
		    # Check whether we are on AC
		    if grep on-line /proc/acpi/ac_adapter/*/state; then
			    # We have permanent power, enable funky savers
			    MODE=""
		    fi
		    su $USER -c "xlock $MODE -display $DISPLAY"
		fi
	fi
else
    # The lid just opened
    # Are we running xscreensaver?
    # We can enable the nice savers now
    if pgrep -U $USER -x xscreensaver; then
	su $USER -c "xscreensaver-command -display $DISPLAY -unthrottle"
    fi
fi
