#!/usr/bin/perl -w

#This ought to work better then Mandrake's default - which doesn't always resume! 
#X often fails to return. So stop X, suspend, resume, continue X. Need to run as root.
#Originally:  XPID=`/sbin/pidof X` ; kill -STOP $XPID ; apm -s ; kill -CONT $XPID 
#Written by Michael Brown <mbrown AT fensystems.co.uk>

use strict;
use POSIX;

# Secure environment and become "proper" root via setuid()
$ENV{PATH} = '/sbin:/bin:/usr/sbin:/usr/bin';
$ENV{ENV} = '';
POSIX::setuid ( 0 ) or die "Could not become root: $!\n";

# Identify PID of X process
chomp ( my $xpid_insecure = `/sbin/pidof X` );
( my $xpid ) = ( $xpid_insecure =~ /^(\d+)$/ );
print "X pid is $xpid\n";

# Switch to VT1, sync disks and kill -STOP X
system ( "/usr/bin/chvt", "1" ); 
system ( "/bin/sync" );
kill "STOP", $xpid or warn "Could not STOP $xpid: $!\n";

# Do the APM suspend
print "About to suspend...\n";
system ( "/usr/bin/apm", "-s" );
print "Resumed\n";

# Kill -CONT X and sync disks again
kill "CONT", $xpid or warn "Could not CONT $xpid: $!\n";
system ( "/bin/sync" );

# Fix up sound. Get alsa to restart, and reload mixer levels.
print "Fixing sound...\n";
system ( "service", "alsa", "restart" ) ==0 or warn "Failed to restart ALSA\n";

#Module stuff below is a workaround for something else which is now fixed. Ignore it.
#Sometimes, cs46xx is loaded. If so, remove to allow snd-cd46xx module to load.
#system ( "rmmod", "cs46xx" ) ==0 or warn "rmmod cs46xx failed\n";
#system ( "modprobe", "snd-cs46xx" ) == 0  or warn "modprobe snd-cs46xx failed\n";
#system ( "alsactl", "restore" ) == 0 or warn "alsactl restore failed\n";

exit
