#!/bin/bash
function killch {
#NOTE: pproc is the pipe process of the dbus-monitor command, 
#      not the dbus-monitor command itself, which is what we need to kill
 mypid=`ps -o pid -o ppid -p $pproc | grep $pproc | awk '{print $2}'`
#echo "mypid is $mypid"
 pchild=$(ps -o pid -o ppid | awk "{if ( \$2 == $mypid ) { print \$1 }}")
 pchild=`echo $pchild | awk '{print $1}'`
#echo "killing $pchild"
 kill $pchild
}

cd `echo $0 | sed -e 's/watchscreensaver//g'`
mypid=$$
ssKdeEnable="false"
ssKdeEnabled=`dcop kdesktop KScreensaverIface isEnabled 2>/dev/null`
if [[ $? != "0" ]]; then
	ssKdeEnabled="false"
fi
if [[ $ssKdeEnabled == "true" ]]; then
    echo "calling kwatchscreensaver-bin"
	exec ./kwatchscreensaver-bin
elif gnome-screensaver-command --query >/dev/null 2>&1 ;then
		echo "calling dbus-monitor"
  		sargs="type='signal',interface='org.gnome.ScreenSaver'"
		cmd="dbus-monitor --session"
		dbus-monitor --session "$sargs" | ./sametime_mongss.sh&
		pproc=$!
		trap "killch" 3 6 9 15 19
		done=0
		while [ ${done} -eq 0 ];
		do
			sleep 30
			parpid=`ps -o ppid ${mypid} | awk '{if(NR == 2) print $1;}'`
			if [ ${parpid} -eq 1 ]; then
				done=1
			fi
		done
		killch
elif xscreensaver-command -version >/dev/null 2>&1 ;then
		#if rc==0, version should be in out file. otherwise it will be empty if there was some error and error in err file
			FILESIZE=$(stat -c%s "/tmp/xscn.out")
			if [[ ${FILESIZE} -ne 0 ]]; then
			echo "calling xscreensaver-command watch"
  			exec xscreensaver-command -watch
  		else
  			exit 1
		fi	
else
		exit 1
fi

