#!/bin/bash
# -*- Mode: shell-script -*-
# Copyright (C) 2003 by MandrakeSoft, Chmouel Boudjnah <chmouel@mandrakesoft.com>
# Redistribution of this file is permitted under the terms of the GNU 
# Public License (GPL)
#
# suspend: 50
# resume: 5

. /etc/sysconfig/suspend

ARG=$1

if [[ -z $(pidof X) ]];then
    exit;
fi

function suspend {
    if [[ -n $CHANGE_VT && $CHANGE_VT != '0' ]];then
	chvt 1
    fi
    if [[ $LOCK_XFREE = "yes" ]];then

        kde_started=$(pidof "kdesktop [kdeinit]")
        if [[ -n $kde_started ]];then 
	    # with KDE it's easy !!!
            dcop --all-sessions --all-users kdesktop KScreensaverIface 'lock()' 2>/dev/null >/dev/null
            return
        fi

	#that include Gnome and you need to use xscreensaver if
	#you want i do some bloody stuff
        xscreensaver_started="$(pidof xscreensaver)"
        if [[ -n $xscreensaver_started ]];then
            for pid in $xscreensaver_started;do
                RUSER=$(perl -an -e 's|.*USER=([^\000]*).*|\1|m;print $_, "\n"' < /proc/$pid/environ)
                RDISPLAY=$(perl -an -e 's|.*DISPLAY=([^\000]*).*|\1|m;print $_, "\n"' < /proc/$pid/environ)
                su $RUSER -c "xscreensaver-command -display $RDISPLAY -lock || (xscreensaver -display $RDISPLAY -no-splash &sleep 1; xscreensaver-command -display $RDISPLAY -lock) || xlock -display $RDISPLAY" & 2>/dev/null >/dev/null
            done
            return
        fi
	#TODO: need to do something when we don't have anything
    fi
}

function resume {
    if [[ -n $CHANGE_VT && $CHANGE_VT != "0" ]];then
	if [[ -n $(pidof X) ]];then
	    chvt "$CHANGE_VT"
	fi
    fi
}

case $ARG in
    suspend)
	suspend
	;;
    resume)
	resume
	;;
esac