#!/bin/bash

#This is RJN's suspend script. The most important thing is to chvt1, then SIGSTOP X before suspending. Otherwise, X won't resume!
#The Mandriva scripts as supplied will cause X to hang. Note: the SIGSTOP-SIGCONT are just "belt and braces" (they were previously
#essential using apm), however, if they *are* used, it is important to avoid race conditions. Avoid either starting the screensaver,
#or chvt 7  during the time when the X-server is frozen: doing so would crash it.

#This script does not co-exist with Mandriva's scripts, especially if using kill -STOP,CONT. Because suspend.control iterates over
#suspend.d/*, it isn't safe to just rename xfree to xfree.old. It must be deleted, or modified to exit immediately. Test for this.
for xfree in /etc/sysconfig/suspend-scripts/suspend.d/xfree*; do
	grep -vE '^#|^[[:space:]]*$|[[:space:]]*echo' $xfree | head -n 1 | grep -Eqv '^[[:space:]]*exit'
	if [ $? == 0 ];then		#match if the script'sfirst instruction (lines other than whitespace,comments,echo) is not "exit".
		echo "Warning: a script /etc/sysconfig/suspend-scripts/suspend.d/xfree* exists and does not exit immediately. Please fix this."
		exit 1 										#Stop, rather than risk a crash.
	fi
done

echo "Sleep button has been pressed."

echo "Syncing Disks"
sync

echo "Ejecting PCMCIA cards (if present)"	#This is harmless if none are present; if they are there, it is necessary to eject
cardctl eject					#them. Otherwise, the system will hang.

echo -n "Locking display(s): "				#For all users who are locally logged in, lock the display.
who | while read line ; do				#Use xscreensaver to do this; start it for them if necessary.
	RUSER=$(echo "$line" | awk '{print $1}')  	#Important: do NOT do this in the background (with &). Otherwise, a race condition
	RDISPLAY=$(echo "$line" | awk '{print $2}')     #occurs between the xscreensaver-lock and the kill -STOP, which will crash X.
	if echo $RDISPLAY | grep -q ':' ; then
		echo "$RUSER on $RDISPLAY "
                su $RUSER -c "xscreensaver-command -display $RDISPLAY -lock || \
                  (xscreensaver -display $RDISPLAY -no-splash & sleep 1; xscreensaver-command -display $RDISPLAY -lock)" 2>&1 >/dev/null
	fi
done
echo ""

echo "Switching to console 1 (chvt 1)"		#Switch to console. This is very important!
chvt 1

echo "Turning off backlight"			#On X22, the backlight doesn't turn off. On A22p, this isn't required, but is harmless.
radeontool light off

echo "Pausing X server (kill -STOP)"		#SIGSTOP X. Not always necessary, but gives extra certainty that X really can't crash.
killall -STOP X

if /etc/init.d/timidity status | grep -q running ; then 	#Must stop the Timidity service or ALSA will fail to shutdown.
    echo "Stopping Timidity"					#If that happens, ALSA won't restart, so no sound on resume.
    service timidity stop
    TIMIDITY_RESTART=true
fi


echo -n "Now suspending to RAM... "		#Actually do it. All the Mandriva suspend scripts (/etc/sysconfig/suspend)
/usr/sbin/pmsuspend2 -d memory			#get invoked here. The resume scripts get invoked on resume.   (-d for debug)

echo "resumed."					#Time passses....we awake. [Press the "Fn" button, or close+open lid]

echo "Turning on backlight"			#Only needed on X22.
radeontool light on

echo "Continuing the X server"			#Restart X.
killall -CONT X

sleep 0.5   					#(just in case.)

echo "Switching back to VT7 (chvt 7)"		#Back to X.
chvt 7

echo "Syncing disks"
sync

echo "Unblanking screensaver(s)"		#Doesn't unlock the screen, but unblanks the screen and shows the password prompt.
who | while read line ; do   			#Otherwise, you'd never know when you needed to wiggle the mouse!
        RUSER=$(echo "$line" | awk '{print $1}')
        RDISPLAY=$(echo "$line" | awk '{print $2}')
        if echo $RDISPLAY | grep -q ':' ; then
                su $RUSER -c "xscreensaver-command -display $RDISPLAY -deactivate"  2>&1 >/dev/null
        fi
done


if [ "$TIMIDITY_RESTART" == true ];then		#If Timidity was running before, then start it up again.
	echo "Starting Timidity"
	sleep 2					#Sleep to allow ALSA to stabilise.
	service timidity start
fi

echo "Restarting the network"			#Restart the network - or the wifi card won't work.
service network restart				#(It will appear ok in ifwconfig, but dhclient will silently fail)

echo "Done"
exit


#Note: on the A22p, there is no need for any special fix for the mouse sensitivity. It remains where it was.
#Otherwise, we'd need to do:   sudo sh -c "echo -n 255 > /sys/devices/platform/i8042/serio0/sensitivity"

