#!/bin/bash

# lid.sh
# Copyright 2003 Rob Mahurin rob@utk.edu
# Changed by Ulrich Dangel uli@spamt.net
# Available for use under the General Public License
# No warranty etc.
   
LOCKCMD=/usr/bin/X11/xlock
XSET=/usr/bin/X11/xset 
# XSET=/bin/false  # uncomment this or something similar to not use DPMS


die() {
    echo "Unable to determine state of lid."
    exit 1
}


runxcmd() (
    
# New loop doesnt work if you login via terminal, use the old instead    
#    for i in /tmp/.X11-unix/X* ; do
#	    USER=$(ps axuf|grep -A1 " :$num" | grep -v -- "X11\|root\|--" |awk '{print $1}' )
#       num=$(basename $i | cut -b2-)
    for num in $(who | grep " :" | awk  '{ print $2 }') ; do
	    USER=$(who | grep " $num" | awk '{ print $1 }')

	if [ !  z"$USER" == z ] ; then
		su - $USER -c "export DISPLAY=$num ; "$@" &"
	fi 
    done
)

RADEONTOOL=/usr/local/bin/radeontool
[ -x $RADEONTOOL ] || exit 0

STATEFILE=/proc/acpi/button/lid/LID/state
[ -f $STATEFILE ] || die;
STATE=$(awk '{ print $2 }' < $STATEFILE)

case "$STATE" in
    "closed")
	$RADEONTOOL light off
	runxcmd $LOCKCMD
	[ -x $XSET ] && runxcmd $XSET dpms force off
        
        ;;
    "open")
	[ -x $XSET ] && runxcmd $XSET dpms force on
        $RADEONTOOL light on
        ;;
    *)
        $RADEONTOOL light on
        die
        ;;
esac

