#!/bin/bash 
# (c) LA Walsh 2004-2014, licenced under GPLv2 
#export DISPLAY=:0
#export XAPPLRESDIR=/usr/X11R6/lib/X11/app-defaults
#export XCMSDB=/usr/X11R6/lib/X11/Xcms.txt
#export XKEYSYMDB=/usr/X11R6/lib/X11/XKeysymDB
#export XNLSPATH=/usr/X11R6/lib/X11/locale
#unexport XAPPLRESDIR XCMSDB XKEYSYMDB XNLSPATH

# see cygwin Xwin for more option examples
# relevant ops:
# -multiwindow = use windows manage; not w/(-rootless|-fullscreen)
# -clipboard = use built-in version (integrated w/windows)
# -unixkill = Enable Ctrl-Alt-BS as X-server shutdown cmnd
# -nowinkill = Disable Alt+F4 as a server shutdown key combination.
# -trayicon = (default) windows tray icon enabled
################################################################################
#set -x
export LIBGL_USE_WGL=1
mount -c /
export PATH=/bin:$(/bin/cygpath "$USERPROFILE")/bin:$PATH	#ensure our bin is 1st
shopt -s expand_aliases extglob
alias my='declare ' int='my -i ' array='my -a ' map='my -A '
alias xset=$(type -P xset);
alias notify=$(type -P notifu)

my HKLM='HKEY_LOCAL_MACHINE' MsWinNT='SOFTWARE/Microsoft/Windows NT'
my DPI_Px='FontDPI/LogPixels' proc_reg='/proc/registry'
my pixels_key="$HKLM/$MsWinNT/CurrentVersion/$DPI_Px"
my pixels_path="$proc_reg/$pixels_key"

export DISPLAY="${DISPLAY:-":0"}"

sub xup() {
	local stat
	read -t .1 stat <<<$(xset q >&/dev/null; echo $?)   && 
				return $stat
	((-1))	
}

Xwin_pids() {
	( cd /proc  && for exe in [0-9]*/exename; do 
			read ln<"$exe"
		 	((${#ln})) && [[ $ln =~ Xwin ]] && printf "%d %s\n" "${i%/*}" "$ln"
		done
	)
}


Xwin_running() { 
	my nam; int pid
	read pid nam< <(Xwin_pids)
	return $((!pid))
}

kill_Xwin() {
	array sigs=(TERM TERM KILL)	# try 2 TERMs then KILL upto maxsigs
	int pd; my pg
	int maxsigs=3 lastsig=${#sigs[*]}
	while ((maxsigs)) && read pd pg; do
		((pd)) && kill -${sigs[--maxsigs>lastsig ? lastsig : maxsigs]} $pd
		sleep 1
	done < <(Xwin_pids)
}

tidy_old_Xwin() {
	rm -fr /tmp/.X11-unix
}

ord() { printf "%d" "'$1" ; }

get_dpi() {
	my dw=""; read -d '' dw< <(<"$pixels_path" cat 2>/dev/null)
	int dpi=$(ord "$dw")
	# check for insane values
 	((dpi<50||dpi>>400)) && dpi=107
	printf ${1:+-v $1} "%d\n" $dpi
}



get_fontpath() {
	printf "%s" "/usr/share/fonts/TTF,/usr/share/fonts/Type1,/usr/share/fonts/misc,/usr/share/fonts/100dpi,built-ins,/windows/fonts"
}

start_XWin() {
	my fontpath=$(get_fontpath)
	int dpi=$(get_dpi)
	cmd="/bin/run /bin/XWin  ${dpi:+-dpi $dpi} -listen tcp  -nopn +iglx -wgl -compositealpha -compositewm -lesspointer -clipboard  -ac -unixkill -nowinkill -multiwindow -wm -ardelay 150 -arinterval 30 +bs -nomultimonitors -hostintitle -noreset -logverbose 2 -fp \"$fontpath\" "
	echo cmd="$cmd"
	$cmd
}

start_syslogd() {
	command cygrunsrv -n -O -S syslogd
}

start_cygserver() {
	command cygrunsrv -n -O -S -d messagebus cygserver
}

start_msgbus() {
	command cygrunsrv -n -O -S -d syslogd messagebus
}

start_sess_dbus() {
	/bin/run /bin/dbus-launch --exit_with_session ~/.Xsession
}


_in() {
	local x=${1:?};shift
	for ((;$#>0;)); do [[ $x == $1 ]] && return 0;shift; done
	return 1
}


int tries=3

if Xwin_running && xup; then
	notify /t info /m "Xserver already running and ready" /d 5000
else 
	#echo "No Xserver detected"
	
	tidy_old_Xwin

	while ((1)); do
		start_cygserver
		start_XWin
		sleep 1
	
		for ((i=0;i<5;++i)); do
			xup && break 2
			sleep 1
		done

		if ((--tries<=0)); then
			m="EXITING: Timeout Waiting for Xserver Startup!!"
			echo "$m"
			notify /t error /m "$m" 
			exit 1;
		fi
	done
	start_sess_dbus
	#start_dbus || { m="Error Starting Dbus"; echo "$m"; notify /t error /m "$m"; }
fi

# vim: ts=2:sw=2
