#!/bin/ash
# wmexit - command to exit from X
# Copyright (C) James Budiono 2012, 2019
# License: GNU GPL Version 3
# Note: a replacement for wmpoweroff, wmreboot and others
#
# parameter: $1 - action, $2 - optional wm, $3 - optional panel
# env DONT_ASK=yes -> no confirmation asked
# action is: poweroff/shutdown, reboot, restart, xorgwizard, terminal, logout

export TEXTDOMAIN=fatdog

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

### configuration
F_EXIT_REASON=/tmp/wmexitmode.$USER.txt	# talk back to xwin of why we're exiting
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
F_XSERVER_PID=/tmp/xinitrc-Xserver.pid.$USER	# defined by xserverrc

### 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="" session_pid=""
	
	ps -o ppid= -C gtk-server | xargs kill 2> /dev/null
	[ -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
	[ -e $F_XSERVER_PID ] && read xserver_pid < $F_XSERVER_PID
	rm -f $F_WINDOW_MANAGER_PID $F_WINDOW_PANEL_PID $F_SESSION_PID $F_XSERVER_PID

	# attempt to kill in order of politeness
	if [ "$session_pid" ]; then
		kill $session_pid
	elif [ "$wm_pid" -o "$panel_pid" ]; then
		kill $wm_pid $panel_pid
	elif [ $xserver_pid ]; then
		kill $xserver_pid
	else
		killall X
	fi
}


########## main ############
[ "$DONT_ASK" ] && DONT_ASK=noprompt
case $1 in 
	poweroff|shutdown)
		# handle directly
		[ $(id -u) -ne 0 ] && exec gtksu "$(TEXTDOMAIN=labels gettext 'Power-off')" "$0" $1
		/sbin/poweroff $DONT_ASK
		;;
		
	reboot)
		# handle directly
		[ $(id -u) -ne 0 ] && exec gtksu "$(TEXTDOMAIN=labels gettext 'Reboot')" "$0" $1
		/sbin/reboot $DONT_ASK
		;;
	
	restart|xorgwizard|terminal|logout)
		if [ "$DISPLAY" ] && [ -z $DONT_ASK ]; then
			! Xdialog --title "$(gettext 'Leave desktop')" --yesno "\
$(gettext 'Do you want to leave desktop and close all applications?')

$(gettext 'All unsaved changes will be lost.')
$(gettext 'Please save all open documents before continuing.')
" 0 0 &&
			return 1
		fi
		# let xwin handle this
		[ $2 ] && echo $2 > $WINDOW_MANAGER_CONFIG
		[ $3 ] && echo $3 > $WINDOW_PANEL_CONFIG
		echo $1 > $F_EXIT_REASON
		stop_X
		;;

	*)	# unknown parameter, try help
		echo "Usage: wmexit shutdown|poweroff|reboot|restart|terminal|logout|xorgwizard"
		;;
esac
