#!/bin/sh
# Copyright (C) James Budiono 2012
# Re-written for Fatdog64 600
# License: GNU GPL Version 3 or later
#
# this file starts the X server via xinit.
#
# why do we need to do this instead of calling xinit directly?
# 1) allow user to start desktop manually when pfix=nox has been given
# 2) do things after X quits (e.g. restart X automatically)
#
# This, together with wmexit, is a poor man's "session manager"
# Don't do too much here (move stuff to either xinitrc or profile) because this
# will not be called when a "real" session manager (e.g. slim) is used.
#
# $1 - window manager, $2 - window panel (both optional) - passed on to xinit
# $3 - X display to use (normally left blank) - used to start 2nd X desktop
#

### configuration
LANG_CONFIG=$FATDOG_STATE_DIR/language	# defined by chooselocale
TZ_CONFIG=$FATDOG_STATE_DIR/timezone	# no apps define this one yet ...
F_EXIT_REASON=/tmp/wmexitmode.$USER.txt # set by wmexit

# don't start X if X is already running
[ -z "$3" ] && pidof X Xorg > /dev/null && exit
echo "Starting X desktop ..."

# Ensure cwd is $HOME, so rox icon and menu item open at home directory
cd $HOME

# start X via xinit 
WM="$1" WP="$2"	# only use the specified param once
while true; do
	rm -f $F_EXIT_REASON 2> /dev/null
	xinit $HOME/.xinitrc "$WM" "$WP" -- $3
	WM="" WP=""
	
	# what to do after exit
    case $(cat $F_EXIT_REASON 2> /dev/null) in 
		terminal|"")		break ;; 	# blank for in case X is killed with Ctrl-Alt-Bksp
		xorgwizard)			xorgwizard; sleep 2 ;;
		restart) 			# update to new language if needed
							[ -e $LANG_CONFIG ] && read NEWLANG < $LANG_CONFIG 
							[ -e $TZ_CONFIG ] && read NEWTZ < $TZ_CONFIG 
							[ "$NEWLANG" -a "$NEWLANG" != "$LANG" ] && export LANG=$NEWLANG 
							[ "$NEWTZ" -a "$NEWTZ" != "$TZ" ] && export TZ=$NEWTZ ;;
		logout)				if ! kill -HUP $(ps -t $(tty) -o pid,stat | awk '/s/ {print $1}'); then
								echo -e "\n\033[1mUnable to logout, you may have started this session using \033[32msu\033[37m."
								echo -e "Type \033[31mexit\033[37m or \033[31mlogout\033[37m at the console instead.\033[m\017\n" 
								exit
							fi
    esac
done
rm -f $F_EXIT_REASON 2> /dev/null

echo 'To restart desktop, type "xwin".'
echo 'To shutdown, type "poweroff", to reboot, type "reboot".'
echo 'If desktop failed to start, type "xorgwizard" to setup.'

