#!/bin/bash

session_dir=/etc/X11/xinit/session.d
xim_dir=/etc/X11/xinit/xim.d
user_session="$HOME/.xinit.d/session"
user_xim="$HOME/.xinit.d/xim"
user_hook="$HOME/.xinit.d/hook"

# make a list of programs to be ignored by the session manager proxy
SESSION_MANAGER_EXCLUDES="ximswitch"
pushd /etc/X11/xinit/xim.d/ > /dev/null
for sc in *; do 
	unset NAME
	unset IFEXISTS
	unset IM_EXEC
	source "$sc"
	for tok in $IM_EXEC; do
		if [ "$tok" = "env" ]; then
			continue
		fi
		if ( echo "$tok" | egrep -q "^.+=.+" ) then
			continue
		fi
		SESSION_MANAGER_EXCLUDES="$SESSION_MANAGER_EXCLUDES $tok"
		break
	done
done
popd > /dev/null
unset NAME
unset IFEXISTS
unset IM_EXEC
unset XMODIFIERS
export SESSION_MANAGER_EXCLUDES

# check im settings
unset IM
if [ -f "$user_xim" ]; then
	IM=`cat "$user_xim" 2> /dev/null`
	if [ -f "$xim_dir/$IM" ]; then
		echo "Reading $xim_dir/$IM"
		source "$xim_dir/$IM"
	else
		echo "Wrong IM is specified in $user_xim"
	fi
fi

# check session settings
if [ -f "$session_dir/$SESSION_TYPE" ]; then
	echo "Reading $session_dir/$SESSION_TYPE"
	source "$session_dir/$SESSION_TYPE"
else
	echo "Wrong session name is specified in $user_session"
	SESSION_EXEC="xterm"
fi

# execute the gnome-setting-daemon if it exists and not KDE or XFce4
if [ "$SESSION_TYPE" != "kde" -a "$SESSION_TYPE" != "xfce4" ]; then
	if [ -x /usr/bin/gnome-settings-daemon ]; then
		echo "Starting gnome-settings-daemon"
		/usr/bin/gnome-settings-daemon &
	fi
fi

# execute im server
if [ -x "/usr/bin/ximswitch" ]; then
	echo "Executing /usr/bin/ximswitch $IM"
	unset XMODIFIERS
	/usr/bin/ximswitch $IM
elif [ "$IM_EXEC" != "" ]; then
	echo "Executing $IM_EXEC"
	$IM_EXEC &
fi

# wait until IM is ready
unset IM_PROC
if echo "$IM_EXEC" | grep -q "httx" ; then
  # ATOKX
  IM_PROC="LookupAux"
  # SKK
  if echo "$IM_EXEC" | grep -q "skk" ; then
    IM_PROC="PaletteAux"
  fi
  if echo "$IM_EXEC" | grep -q "canna" ; then
    IM_PROC="PaletteAux"
  fi
fi
if [ "$IM_PROC" != "" ]; then
  times=0
  until ps xc | grep -q "$IM_PROC" ; do
    # timeout in 30sec
    if [ $times -ge 30 ]; then break ; fi
    times=$[$times+1]
    sleep 1
  done
  sleep 1
  unset times
fi

# execute user hook
if [ -x "$user_hook" ]; then
	source "$user_hook";
fi

# execute the specified session manager
echo "Starting $SESSION_EXEC"
exec $SESSION_EXEC
echo "Failed"

