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

# 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.

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")); }

FixBrowser()
{
    BROWSER="kfmclient openProfile webbrowsing"
    HELP_BROWSER="kfmclient openProfile webbrowsing"
}

# 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

# fix $BROWSER
if [ -n "$BROWSER" ]; then
    if [ "$BROWSER" == "/usr/bin/xbrowser" -a -L /usr/bin/xbrowser ]; then
	[ "$(readlink `readlink /usr/bin/xbrowser`)" == "$KDEDIR""/bin/konqueror" ] && FixBrowser
    else	
	[ "$BROWSER" == "$KDEDIR""/bin/konqueror" ] && FixBrowser
    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=$KDE_ALT_DATA/desktoplnk
CONF_SKEL=$KDE_ALT_DATA/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 /var/tmp and "$HOME" and for write access
#  error exit, if not
for d in /tmp /var/tmp "$HOME"
do
    if [ `LC_ALL=C df -m "$d"| tail -1 | xargs | cut -d" " -f4` -lt 25 ]; then
	xmessage -center "Not enough free disk space on $d"
	exit 1
    fi

    testfile=`mktemp "$d"/KDE.startkde.XXXXXX`
    if ! echo TEST_TEXT >$testfile 2>/dev/null ; then
	xmessage -center "You don't have write permissions for $d"
	exit 1
    fi
    rm -f $testfile
done

# create necessary directories/files
if ! [ -e "$HOME"/.smb/smb.conf ]; then
    mkdir -p "$HOME"/.smb
    >"$HOME"/.smb/smb.conf
    if [ "$KDELANG" == "ru" -o "$KDELANG" == "uk" -o  "$KDELANG" == "be" ]
    then
	cat >"$HOME"/.smb/smb.conf <<__EOF__
# added by startkde
[global]
dos charset = CP866
__EOF__
    fi
fi

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

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

# 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

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

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

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

# the splashscreen and progress indicator
ksplash --nodcop

# 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

# 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^:^ ^g'`
do 
  for file in $prefix/*
  do 
    if test -x $file
    then 
       $file
    fi
  done
done

echo 'startkde: Done.'  1>&2
