#!/bin/dash
# Copyright (C) James Budiono 2012, 2013
# Special version of xwin for Fatdog64 Sandbox
# License: GNU GPL Version 3 or later
#
# This file starts the X server via xinit.
# This is a simplified version of the real xwin.
# It doesn't handle X server restart. 
#
# $1 - window manager, $2 - window panel (both optional) - passed on to xinit
#

### configuration
WINDOW_SIZE=${WINDOW_SIZE:-1024x600}

# don't start if there is no parent display
[ -z "$DISPLAY" ] && exit
echo "Starting X desktop ..."

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

# find free display number
for disp in $(seq 1 10); do
	[ ! -e /tmp/.X${disp}-lock ] && break
done
export SANDBOX_DISPLAY=${disp} # for use by sandbox-wmexit

# hack because Xephyr sometimes crash the first time
if ! [ -e /etc/.XLOADED ]; then
	Xephyr :$disp &
	XPID=$!
	sleep 1
	kill $XPID
	rm -f /tmp/.X11-unix/X${disp} /tmp/.X${disp}-lock	
	touch /etc/.XLOADED
fi

# start X via xinit 
xinit $HOME/.xinitrc "$1" "$2" -- \
/usr/bin/Xephyr :$disp -ac -host-cursor -screen $WINDOW_SIZE -keybd ephyr,,xkbmodel=evdev,xkbrules=evdev > /dev/null &
xinit_pid=$!

# this is complicated way to get the XSESSION_ID from outside
sleep 3 # wait for the whole setup to start
xserver_pid=$(netstat -ap | sed -n "\_/tmp/.X11-unix/X${SANDBOX_DISPLAY}_ {s|.*[^0-9]\([0-9][0-9]*/Xephyr\).*|\1|;s|/Xephyr||;p;q}")
# find child of xinit which isn't the X server
xinit_child=$(ps -eo pid,ppid | awk -v xserver_pid=$xserver_pid -v xinit_pid=$xinit_pid '$1 != xserver_pid && $2==xinit_pid { print $1 }')
XSESSION_ID=$(tr '\000' '\n' < /proc/$xinit_child/environ | sed -n '/^XSESSION_ID=/ {s/XSESSION_ID=//;p;q}')
#echo $XSESSION_ID

# wait for xinit to finish before cleaning up
wait $xinit_pid
rm -f /tmp/.X11-unix/X${disp}
rm -f /tmp/.X${disp}-lock
rm -f /tmp/*.pid.$USER.$XSESSION_ID	# clean up stuff

echo 'To restart desktop, type "xwin".'
echo 'To leave sandbox, type "poweroff".'
