#!/bin/dash
# rc.Xstartwm (aka restartwm) - start window manager and panel
# as "restartwm", it will hot-restart window managers (without X restart)
# Copyright (C) James Budiono 2019
# License: GNU GPL Version 3
#
# parameter (all optional): # $1-window manager $2-panel $3-"cold" restart

### configuration
# fallback defaults
WINDOW_MANAGER=openbox
WINDOW_PANEL=defaultpanel

# system defaults
[ -r /etc/windowmanager ] && read WINDOW_MANAGER < /etc/windowmanager
[ -r /etc/windowpanel ] && read WINDOW_PANEL < /etc/windowpanel

# per-user default
WINDOW_MANAGER_CONFIG=$FATDOG_STATE_DIR/windowmanager
WINDOW_PANEL_CONFIG=$FATDOG_STATE_DIR/windowpanel

# used by wmexit
F_WINDOW_MANAGER_PID=/tmp/xinitrc-wm.pid.$USER.$XSESSION_ID
F_WINDOW_PANEL_PID=/tmp/xinitrc-panel.pid.$USER.$XSESSION_ID



###### main ######

### as "restartwm", stop current wm
case "$0" in *restartwm)
# restart X if "cold" option is given
[ "$3" = cold ] && exec wmexit restart "$@"

# or else just kill the current wm and panel
[ -e $F_WINDOW_MANAGER_PID ] && read wm_pid < $F_WINDOW_MANAGER_PID
[ -e $F_WINDOW_PANEL_PID ] && read panel_pid < $F_WINDOW_PANEL_PID
[ "$wm_pid" ] && kill "$wm_pid" && wait "$wm_pid"
[ "$panel_pid" ] && kill "$panel_pid" && wait "$panel_pid"

echo Waiting for previous window manager to terminate ...
sleep 1
esac

### launch new wm
[ "$1" ] && echo "$1" > $WINDOW_MANAGER_CONFIG
[ "$2" ] && echo "$2" > $WINDOW_PANEL_CONFIG
[ -e $WINDOW_MANAGER_CONFIG ] && read WINDOW_MANAGER < $WINDOW_MANAGER_CONFIG
[ -e $WINDOW_PANEL_CONFIG ] && read WINDOW_PANEL < $WINDOW_PANEL_CONFIG

rm -f $F_WINDOW_MANAGER_PID $F_WINDOW_PANEL_PID
case "$WINDOW_MANAGER" in
	jwm|icewm|icewm-session)
		[ "$WINDOW_MANAGER" = jwm ] && fixmenus
		"$WINDOW_MANAGER" &
		echo $! > $F_WINDOW_MANAGER_PID
		;;
	*)	# all others: openbox, etc
		if [ "$WINDOW_PANEL" ]; then
			"$WINDOW_PANEL" &
			echo $! > $F_WINDOW_PANEL_PID
		fi
		"$WINDOW_MANAGER" &
		echo $! > $F_WINDOW_MANAGER_PID
		;;
esac

# done
