#!/bin/bash

#try to exit as nicely as possible
#any weird race conditions or corner cases might slip past - groovix-session-forced-exit will take care of those

CURUSER=`cat /var/lib/groovix/session-info/current-user`

#see if we're actually into the xfce session
if [ -e /var/lib/groovix/session-info/session-setup-completed ] ;  then

	# if we're not running xfce don't try to kill it
	egrep "^\s*user-session=groovix-fullscreen-kiosk-session" /etc/lightdm/lightdm.conf
	if [ $? -eq 0 ] ; then
		echo stopping groovix fullscreen kiosk session
		killall groovix-fullscreen-kiosk-session
	else
		echo stopping xfce
		if [ `whoami` = "root" ] ; then
			MYDISPLAY=`cat /var/lib/groovix/session-info/current-display`
			export DISPLAY=:$MYDISPLAY

			#in 16.04 this causes a "could not get owner of name" error popup while logout is processing
			#su `cat /var/lib/groovix/session-info/current-user` -c "xfce4-session-logout --logout --fast"
			#pkill -SIGTERM -f xfce4-session

			# not safe since we're sourcing something user could write
			#. $(cat /var/lib/groovix/session-info/current-home)/.xsession-export

			# found this by searching on cron dbus address , also can get from /proc/$p/environ where $p is xfce pids
			export DBUS_SESSION_BUS_ADDRESS="$(ps -u $CURUSER e | grep -Eo 'dbus-daemon.*address=unix:abstract=/tmp/dbus-[A-Za-z0-9]{10}' | tail -c35)"
			su $CURUSER -c "xfce4-session-logout --logout --fast"
			
			
		else
			#in 16.04 this causes a "could not get owner of name" error popup while logout is processing
			#xfce4-session-logout --logout --fast
			#pkill -SIGTERM -f xfce4-session

			# not safe since we're sourcing something user could write
			#. ~/.xsession-export

			# found this by searching on cron dbus address , also can get from /proc/$p/environ where $p is xfce pids
			# running as actual user, so use USER instead of $CURUSER, although either should work
			export DBUS_SESSION_BUS_ADDRESS="$(ps -u $USER e | grep -Eo 'dbus-daemon.*address=unix:abstract=/tmp/dbus-[A-Za-z0-9]{10}' | tail -c35)"
			xfce4-session-logout --logout --fast
		fi
	fi
else
	#if we're still in the session-startup phase, we'll have to kill it to abort
	killall groovix-session-startup
	killall -9 groovix-session-startup
fi
