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

# 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 left 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.
#
# Set the background to plain grey.
# The standard X background is nasty, causing moire effects and exploding
# people's heads. We use colours from the standard KDE palette for those with
# palettised displays.

# 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 "$KDEHOME" ]      && KDEHOME=$HOME/.kde || KDEHOME=`echo "$KDEHOME"|sed "s,^\~/,$HOME/,"`
kdehome=$KDEHOME
[ -z "$KDEDIR" ]       && KDEDIR=/usr
[ -z "$TMPDIR" ]       && KDETMP=/tmp || KDETMP=$TMPDIR
BROWSER="kfmclient openProfile webbrowsing"
HELP_BROWSER="kfmclient openProfile webbrowsing"

export KDEDIR KDEHOME KDETMP BROWSER HELP_BROWSER

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=`df -m /tmp | xargs | cut -d" " -f11`
space_home=`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
  /usr/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 /dev/dsp ] && [ ! -e $KDEHOME/share/config/kcmartsrc ] ; then
	echo "[Arts]" > $KDEHOME/share/config/kcmartsrc
	echo "StartServer=false" >> $KDEHOME/share/config/kcmartsrc
fi

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

# Dadou 2.1.1-9mdk - Create directory for bokkmakrs and copy them
if [ ! -d $KDEHOME/share/apps/konqueror ] ; then
        mkdir -p $KDEHOME/share/apps/konqueror/ && cp /usr/share/alt/kde/bookmarks.xml $KDEHOME/share/apps/konqueror/
fi

# Dadou - 2.1.1-4mdk - Force icons alignement to verticaly (work around for a
#                      kdesktop's bug: at first startup, icons are always
#                      horizontaly aligned, even if we want a vertical
#                      alignement).
if [ ! -e $HOME_DESKTOP/.ArrangeIcons ]
    then
       cp /usr/share/alt/kde/ArangeIcons.desktop $HOME_AUTOSTART && touch $HOME_DESKTOP/.ArrangeIcons
    else
	rm -f $HOME_AUTOSTART/ArangeIcons.desktop
fi

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 /usr/bin/ksplashml || 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

# 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

[ -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
