#!/bin/bash -login
#
# .xsession
#

#
# If ssh is configured and ssh-agent is wanted set "yes"
#
usessh="no"

#
# What we do if we fail at least ... emergency fall back.
#
failsafe="xterm -ls -T Failsave -geometry 80x24-0-0"
trap "exec $failsafe" EXIT SIGHUP SIGINT SIGPIPE SIGTERM SIGIO

#
# Some bash (1 and 2) settings to avoid trouble on a
# failed program call.
#
test -n "$BASH" && set +o posix
no_exit_on_failed_exec=1
type shopt > /dev/null 2>&1 && shopt -s execfail

#
# Read system and user profile if not already done
#
if test "$XSESSION_IS_UP" != "yes" ; then
    test -r /etc/profile     && { . /etc/profile     > /dev/null 2>&1 ; }
    test -r ${HOME}/.bashrc  && { . ${HOME}/.bashrc  > /dev/null 2>&1 ; }
    test -r ${HOME}/.profile && { . ${HOME}/.profile > /dev/null 2>&1 ; }
    set +u > /dev/null 2>&1
fi

#
# Read the profile of tcsh users
#
if test "$SHELL" = "/bin/tcsh" ; then
    CSHENV="`$SHELL -c 'test -r $HOME/.login && source /etc/csh.login;
			test -r $HOME/.login && source $HOME/.login;
			printenv'`"
    OLDIFS="$IFS"
    IFS="`echo -en '\r\n\000'`"
    for env in $CSHENV ; do
	var="${env%%=*}" ; val="${env#*=}"
	test "$var" = "$val" && continue
	eval export $var="\$val"
    done
    IFS="$OLDIFS"
fi

#
# Run ssh-agent only if ssh is configured and avaliable.
#
sshagent="no"
if test "$usessh" = "yes" -a -d $HOME/.ssh ; then
	type ssh-agent > /dev/null 2>&1 && sshagent="yes"
fi

if test -f $HOME/.xinitrc ; then
    if test "$sshagent" = "yes" ; then
	exec ssh-agent $HOME/.xinitrc
    else
	exec /bin/bash $HOME/.xinitrc
    fi
else
    if test -z "$WINDOWMANAGER" ; then
        WINDOWMANAGER=/usr/X11R6/bin/kde
    fi
    exec $WINDOWMANAGER
fi

# call failsafe
exit 0
