#!/bin/sh

if [ -f $HOME/.xinitrc ] ; then
    mv $HOME/.xinitrc $HOME/.xinitrc.usekde
fi

if [ -f $HOME/.xsession ] ; then
    mv $HOME/.xsession $HOME/.xsession.usekde
fi

if [ -f $HOME/.Xclients ] ; then
    mv $HOME/.Xclients $HOME/.Xclients.usekde
fi

if [ -f /etc/X11/wdm/Xclients ] ; then
    source=/etc/X11/wdm/Xclients
elif [ -f /etc/X11/xinit/Xclients ] ; then
    source=/etc/X11/xinit/Xclients
else
source=/tmp/usekde.$$
trap "rm -f $source" 0 1 2 3 4 5 6 7 8 9

cat > $source <<'EOD'
#!/bin/bash

# start kinput2
if [ -x /usr/X11R6/bin/kinput2 ] ; then
    /usr/X11R6/bin/kinput2 &
    XMODIFIERS="@im=kinput2"
    TK_KCPROTO=kinput2
    export XMODIFIERS TK_KCPROTO
fi

# First thing - check the user preferences
if [ -f $HOME/.wm_style ] ; then
    WMSTYLE=`cat $HOME/.wm_style`
    case "$WMSTYLE" in 
	kde | KDE)
	    exec $KDEDIR/bin/startkde
	    ;;
	Afterstep | AfterStep)
	    exec /usr/X11R6/bin/RunWM --AfterStep
	    ;;
	WindowMaker | Windowmaker | WMaker |  wmaker)
	    exec /usr/X11R6/bin/RunWM --WindowMaker
	    ;;
	Fvwm95 | fvwm95)
	    exec /usr/X11R6/bin/RunWM --Fvwm95
	    ;;
	Mwm | MWM | Lesstif)
	    exec /usr/X11R6/bin/RunWM --FvwmMWM
	    ;;
    esac
fi

# Default: WindowMaker
/usr/X11R6/bin/RunWM --WindowMaker || {
    # gosh, neither fvwm95 nor fvwm2 is available;
    # let's try regular fvwm (AnotherLevel doesn't work with fvwm1).
    if [ -n "$(type -path fvwm)" ]; then
	# if this works, we stop here
	exec fvwm
    fi

    # wow, fvwm isn't here either ... 
    # use twm as a last resort.
    xterm &
    exec twm
}
EOD
fi

if ! grep -qw bin/startkde $source ; then
    awk '
    /case.*WMSTYLE.*in/ {
	print $0
	print "\tkde | KDE)"
	print "\t    exec $KDEDIR/bin/startkde"
	$0 = "\t    ;;"
    }
    {
	print $0
    }
    ' < $source > $HOME/.Xclients
else
    cp $source $HOME/.Xclients
fi
chmod 755 $HOME/.Xclients

if [ -f $HOME/.wm_style ] ; then
    mv $HOME/.wm_style $HOME/.wm_style.usekde
fi

echo "KDE" > $HOME/.wm_style

