#!/bin/ash
# wmexit - command to exit from X, simplified for Fatdog64 710 UML
# Copyright (C) James Budiono 2012, 2013, 2014, 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() {
	[ -z "$XSESSION_ID" ] && return # can't kill if we don't know the XSESSION_ID
	
	local sesssion_pid=""
	[ -e $F_SESSION_PID ] && read session_pid < $F_SESSION_PID
	rm -f /tmp/*${XSESSION_ID}* # cleanup
		
	if [ "$session_pid" ]; then
		kill $session_pid
	else
		kill $(grep -Fl $XSESSION_ID /proc/*/environ | sed 's|/proc/||;s|/environ||')
	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?')" 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
