#!/bin/bash

REASON=$1

#rotate log
LOG=/var/log/groovix/session-forced-exit.log
mv $LOG.6 $LOG.7
mv $LOG.5 $LOG.6
mv $LOG.4 $LOG.5
mv $LOG.3 $LOG.4
mv $LOG.2 $LOG.3
mv $LOG.1 $LOG.2
mv $LOG $LOG.1

#log everything
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>$LOG 2>&1

. /usr/share/groovix/global.conf

echo $0 launched by: $(cat /proc/$PPID/cmdline) 

if [ -n "$REASON" ] ; then
	groovix-root-run-in-display zenity --error --title "closing session" --text "$REASON" &
	#give them a few seconds to see why they're getting booted
	sleep 20
fi

if [ -e /var/lib/groovix/session-info/session-setup-started ] ; then
	echo "there is a session that needs to be terminated"
else
	echo "there is no session running"
	exit 0
fi

TSTAMP_OLD=`stat -c %Y /var/lib/groovix/session-info/session-setup-started`

groovix-session-exit &

#we have 10 seconds for that to complete

#if we were still in the session setup, groovix-session-exit kills the session setup process which in turn kills this process
#but after forced user logout forced logout, this process lives

#need to know if the session was ended or not since this was called - 
#if groovix-session-exit works, this script should be killed when x dies so we dont' have to wait the full 30 seconds
echo sleeping 10
sleep 10


TSTAMP_NEW=`stat -c %Y /var/lib/groovix/session-info/session-setup-started`

echo debug old $TSTAMP_OLD new $TSTAMP_NEW

if [ x"$TSTAMP_OLD" = x"$TSTAMP_NEW" ] ; then
	echo "session is still running and needs to be terminated"
	echo groovix-session-kill 
	groovix-session-kill &
else
	echo "session has already been terminated"
fi

#this REALLY hoses things up for some video cards, don't use it
#echo sleeping 10
#sleep 10
##bring out the big guns
##forcefully end the desktop session with SAK
#echo echo k \> /proc/sysrq-trigger
#echo k > /proc/sysrq-trigger
#
