#!/bin/ash
# wmexit - command to exit from X - special version for Fatdog64 Sandbox
# Copyright (C) James Budiono 2012, 2013, 2019
# License: GNU GPL Version 3
# Note: a replacement for wmpoweroff, wmreboot and others
#
# parameter: $1 - action, $2 - optional wm, $3 - optional panel
# action is: poweroff/shutdown, reboot, restart, xorgwizard, terminal, logout
#
# Note: this code was only used for the insecure desktop emulation (done 
#       by sharing /tmp), which has been removed from sandbox-lxc.
#       The secure way of desktop emulation uses network Xephyer just like
#       how UML does it, so now sandbox-lxc uses wmexit from UML.

### configuration
WINDOW_MANAGER_CONFIG=$FATDOG_STATE_DIR/windowmanager
WINDOW_PANEL_CONFIG=$FATDOG_STATE_DIR/windowpanel
. $BOOTSTATE_PATH

### configuration
F_SESSION_PID=/tmp/xinitrc-session.pid.$USER.$XSESSION_ID		# defined by xinitrc
F_WINDOW_MANAGER_PID=/tmp/xinitrc-wm.pid.$USER.$XSESSION_ID		# defined by restartwm
F_WINDOW_PANEL_PID=/tmp/xinitrc-panel.pid.$USER.$XSESSION_ID	# defined by restartwm

### utilities - stop X server 
# stop by stopping the window manager if possible (this is more polite)
# kill X if it's not possible
stop_X() {
	local wm_pid="" panel_pid="" xserver_pid="" sesssion_pid=""
	
	[ -e $F_SESSION_PID ] && read session_pid < $F_SESSION_PID
	[ -e $F_WINDOW_MANAGER_PID ] && read wm_pid < $F_WINDOW_MANAGER_PID
	[ -e $F_WINDOW_PANEL_PID ] && read panel_pid < $F_WINDOW_PANEL_PID
	xserver_pid=$(netstat -x | sed -n "\_/tmp/.X11-unix/X${SANDBOX_DISPLAY}_ {s|.*[^0-9]\([0-9][0-9]*/Xephyr\).*|\1|;s|/Xephyr||;p;q}")
	rm -f $F_WINDOW_MANAGER_PID $F_WINDOW_PANEL_PID $F_SESSION_PID
	
	if [ "$session_pid" ]; then
		kill $session_pid
	elif [ "$wm_pid" -o "$panel_pid" ]; then
		#rm -f /tmp/*.pid.$USER.$XSESSION_ID	# clean up stuff
		kill $wm_pid $panel_pid
	elif [ $xserver_pid ]; then
		kill $xserver_pid
	else
		killall Xephyr
	fi
}


########## main ############
case $1 in 	
	restart|xorgwizard|terminal|logout)
		# let xwin handle this
		[ $2 ] && echo $2 > $WINDOW_MANAGER_CONFIG
		[ $3 ] && echo $3 > $WINDOW_PANEL_CONFIG
		stop_X
		;;
		
	poweroff|shutdown|reboot)
		[ $(id -u) -ne 0 ] && exec gtksu "Reboot" "$0" $1
		/sbin/poweroff
		;;
		
	*)	# unknown parameter, try help
		echo "Usage: wmexit shutdown|poweroff|reboot|restart|terminal|logout|xorgwizard"
		;;
esac
