#!/bin/sh
#
#  DEFAULT KDE STARTUP SCRIPT ( KDE-3.1.4 )
#

# When the X server dies we get a HUP signal from xinit. We must ignore it
# because we still need to do some cleanup.
trap 'echo GOT SIGHUP' HUP

# Boot sequence:
#
# kdeinit is used to fork off processes which improves memory usage
# and startup time.
#
# * kdeinit starts the dcopserver and klauncher first.
# * Then kded is started. kded is responsible for keeping the sycoca
#   database up to date. When an up to date database is present it goes
#   into the background and the startup continues.
# * Then kdeinit starts kcminit. kcminit performs initialisation of
#   certain devices according to the user's settings
#
# * Then ksmserver is started which in turn starts
#   1) the window manager (kwin)
#   2) everything in $KDEDIR/share/autostart (kdesktop, kicker, etc.)
#   3) the rest of the session.

# Set a watch cursor instead of the standard X11 "X" cursor, since I've heard
# from some users that they're confused and don't know what to do. This is
# especially necessary on slow machines, where starting KDE takes one or two
# minutes until anything appears on the screen.

if ! [ -e ~/.Xresources ]
then
    echo -e "! Xcursor theme added by /usr/bin/startkde\nXcursor.theme: crystalsvg" >~/.Xresources
    export XCURSOR_THEME=crystalsvg
fi
xsetroot -cursor_name watch

# Set lang and according locale
#SourceIfNotEmpty /etc/profile.d/lang.sh

SourceIfNotEmpty()
{
	local f="$1"
	shift
	[ -s "$f" ] && . "$f" "$@"
}

ExecIfExecutable()
{
	local f="$1"
	shift
	[ -x "$f" ] && "$f" "$@"
}

Quote(){ echo "$@" |sed -e 's/[\&;()<>!|{}?*`"'\''[:space:]]/\\&/g' || return 1; }

ReadConfig(){ eval echo $(Quote $($KDEDIR/bin/kreadconfig --file "$1" --group "$2" --key "$3" --default "$4")); }

# The user's personal KDE directory is usually ~/.kde, but this setting
# may be overridden by setting KDEHOME.
[ -z "$KDEDIR" ] && KDEDIR=/usr
if [ -z "$KDEHOME" ]; then  KDEHOME=$HOME/.kde; else KDEHOME=`echo "$KDEHOME"|sed "s,^\~/,$HOME/,"`; fi
if [ -n "$TMPDIR" ]; then KDETMP=$TMPDIR; else KDETMP=/tmp; fi
if [ -x "$KDEDIR"/bin/kfmclient ]
then
    BROWSER="kfmclient openProfile webbrowsing"
    HELP_BROWSER="kfmclient openProfile webbrowsing"
else
    if [ -x /usr/bin/url_handler.sh ]
    then
	BROWSER="/usr/bin/url_handler.sh"
	HELP_BROWSER="/usr/bin/url_handler.sh"
    else
	BROWSER="/usr/bin/mozilla"
	HELP_BROWSER="/usr/bin/mozilla"
    fi
fi

export KDEDIR KDEHOME KDETMP BROWSER HELP_BROWSER

KDELANG=`echo $LANG|sed "s/_.*//"`
[ -z "$KDE_ALT_DATA" ] && KDE_ALT_DATA=/usr/share/alt/kde
DESK_SKEL=$KDEDIR/share/alt/kde/desktoplnk
CONF_SKEL=$KDEDIR/share/alt/kde/userconfig

# Clean up old kde /tmp files that belong to the user
real_display=`echo $DISPLAY | sed "s/://" | sed "s/\..*//"`
dcop_srv_prefix=$HOME/.DCOPserver_`/bin/hostname`
rm -f "$dcop_srv_prefix" \
 "$dcop_srv_prefix"_:"$real_display" \
 "$dcop_srv_prefix"__"$real_display"

for i in /tmp/.ICE-unix/* /tmp/.ICE-unix/.[0-1,a-z,A-Z]* ; do
	[ -O $i ] && rm -f $i
done

# check for space on /tmp and "$HOME" and for write access
#  error exit, if not
space_tmp=`LC_ALL=C df -m /tmp | xargs | cut -d" " -f11`
space_home=`LC_ALL=C df -m "$HOME" | xargs | cut -d" " -f11`

if [ $space_tmp -lt 25 ]; then
    xmessage -center "Not enough free disk space on /tmp"
    exit 1
fi

if [ $space_home -lt 50 ]; then
    xmessage -center "Not enough free disk space on "$HOME""
    exit 1
fi
testfile_tmp=`mktemp /tmp/KDE.startkde.XXXXXX`
testfile_home=`mktemp "$HOME"/KDE.startkde.XXXXXX`

if ! echo TEST_TEXT >$testfile_tmp 2>/dev/null ; then
    xmessage -center "You don't have write permissions for /tmp"
    exit 1
fi
rm -f $testfile_tmp

if ! echo TEST_TEXT >$testfile_home 2>/dev/null ; then
     xmessage -center "You don't have write permissions for "$HOME""
 exit 1
fi
rm -f $testfile_home

# create necessary directories/files
mkdir -p $KDEHOME/share/config

if ! [ -x $KDEDIR/bin/kreadconfig ]
then 
    xmessage -center "Could not execute $KDEDIR/bin/kreadconfig. Check installation of kdebase package."
    exit 1
fi

HOME_DESKTOP=`ReadConfig kdeglobals Paths Desktop "$HOME/Desktop"`

if [ ! -d "$HOME_DESKTOP" -a -d "$DESK_SKEL" ]; then
  mkdir -p $HOME_DESKTOP
  ( cd $DESK_SKEL && tar cpf - * ) | ( cd $HOME_DESKTOP && tar xpf - )
fi

if [ ! -d "$KDEHOME" -a -d $CONF_SKEL/.kde ]; then
  ( cd $CONF_SKEL/.kde && tar cpf - .kde ) | ( cd $KDEHOME && tar xpf - )
fi

if [ ! -e "$KDEHOME"/share/config/emaildefaults ]; then
  $KDEDIR/bin/mailsettings >"$KDEHOME"/share/config/emaildefaults
fi

if [ ! -e "$KDEHOME"/share/config/kmailrc ]; then
  cat >"$KDEHOME"/share/config/kmailrc <<EOF
[General]
transports=1

[Transport 1]
host=/usr/sbin/sendmail
name=Sendmail
type=sendmail
EOF
fi

if [ ! -e "$KDEHOME"/share/config/kcmlaptoprc -a -e /proc/apm ]; then
  # Try to figure out if we're on a laptop
  if ! /bin/cat /proc/apm |grep -q "?"; then
    # We appear to be on a laptop with battery status notification
    cat >"$KDEHOME"/share/config/kcmlaptoprc <<EOF
[BatteryDefault]
Enable=true
EOF
  fi
fi

if [ ! -f "$HOME"/.kderc -a -e $CONF_SKEL/.kderc ]; then
  cp $CONF_SKEL/.kderc "$HOME"
  chmod 0600 "$HOME"/.kderc
fi

if [ ! -e $KDEHOME/share/config/kcmartsrc ]
then
    if /sbin/lsmod | grep '\[snd-' >/dev/null
    then
	echo -e "[Arts]\nStartServer=false" > $KDEHOME/share/config/kcmartsrc
    fi
fi

HOME_AUTOSTART=`ReadConfig kdeglobals Paths Autostart "$KDEHOME/Autostart"`
mkdir -p $HOME_AUTOSTART

# Create directory for bookmarks and copy them
if [ ! -d $KDEHOME/share/apps/konqueror ] ; then
        mkdir -p $KDEHOME/share/apps/konqueror/
	if [ -f "$KDE_ALT_DATA"/bookmarks-"$KDELANG".xml ]
	then
	    cp "$KDE_ALT_DATA"/bookmarks-"$KDELANG".xml $KDEHOME/share/apps/konqueror/bookmarks.xml
	else
	    cp "$KDE_ALT_DATA"/bookmarks.xml $KDEHOME/share/apps/konqueror/bookmarks.xml
	fi
fi

# Launch gpg-agent
if [ -f "$HOME"/.gnupg/gpg-agent.conf -a -x /usr/bin/gpg-agent -a -z "$GPG_AGENT_INFO" ]
then
    eval "$(/usr/bin/gpg-agent --daemon)"
    GPG_AGENT_PID=`pidof gpg-agent| /bin/sed "s/\ .*//"`
fi

# Link "tmp" resource to directory in /tmp
# Creates a directory /tmp/kde-$USER and links $KDEHOME/tmp-$HOSTNAME to it.
lnusertemp tmp >/dev/null

# Link "socket" resource to directory in /tmp
# Creates a directory /tmp/ksocket-$USER and links $KDEHOME/socket-$HOSTNAME to it.
lnusertemp socket >/dev/null

# In case of dcop sockets left by a previous session, cleanup
dcopserver_shutdown

echo 'startkde: Starting up...'  1>&2

# Start ksplashml or ksplash
ExecIfExecutable $KDEDIR/bin/ksplashml || $KDEDIR/bin/ksplash

# We set LD_BIND_NOW to increase the efficiency of kdeinit.
# kdeinit unsets this variable before loading applications.
LD_BIND_NOW=true kdeinit +kcminit +knotify
if test $? -ne 0; then
  # Startup error
  echo 'startkde: Could not start kdeinit. Check your installation.'  1>&2
  xmessage -center "Could not start kdeinit. Check your installation."
fi

# Scanning netscape plugins
if [ "`ReadConfig kcmnspluginrc Misc startkdeScan false`" == "true" ]
    then
	[ -x $KDEDIR/bin/nspluginscan ] && $KDEDIR/bin/nspluginscan
fi    

xsetroot -cursor_name left_ptr

# finally, give the session control to the session manager
# if the KDEWM environment variable has been set, then it will be used as KDE's
# window manager instead of kwin.
# if KDEWM is not set, ksmserver will ensure kwin is started.
# kwrapper is used to reduce startup time and memory usage
# kwrapper does not return usefull error codes such as the exit code of ksmserver.
# We only check for 255 which means that the ksmserver process could not be 
# started, any problems thereafter, e.g. ksmserver failing to initialize, 
# will remain undetected.
test -n "$KDEWM" && KDEWM="--windowmanager $KDEWM"
kwrapper ksmserver $KDEWM 
if test $? -eq 255; then
  # Startup error
  echo 'startkde: Could not start ksmserver. Check your installation.'  1>&2
  xmessage -center "Could not start ksmserver. Check your installation."
fi

echo 'startkde: Shutting down...'  1>&2

# Stop gpg-agent
[ -n "$GPG_AGENT_PID" ] && kill -TERM $GPG_AGENT_PID

# Clean up
kdeinit_shutdown
dcopserver_shutdown
artsshell -q terminate

echo 'startkde: Running shutdown scripts...'  1>&2

# Run scripts found in $KDEDIRS/shutdown
for prefix in `kde-config --path exe| sed -e 's^bin/^shutdown/^g;s^:^ ^'`
do 
  for file in $prefix/*
  do 
    if test -x $file
    then 
       $file
    fi
  done
done

echo 'startkde: Done.'  1>&2
