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

# check for already running KDE
dcop kdesktop KDesktopIface isVRoot >/dev/null 2>/dev/null;
if test "$?" = 0; then
  echo "ERROR: KDE seems already running on this display."
  xmessage -geometry 500x100 "ERROR: KDE seems already running on this display."
  exit 1
fi

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

# 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

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

#
# The user's personal KDE directory is usually $HOME/.kde3, but this setting
# may be overridden by setting KDEHOME.
#
[ "$QTDIR" != /usr/lib/qt3 ] && unset QTDIR
unset KDEDIR
unset KDEDIRS
KDEMAINDIR=/opt/kde3/
# The user's personal KDE directory is usually ~/.kde, but this setting
kdehome=$HOME/.kde
test -n "$KDEHOME" && kdehome=`echo "$KDEHOME"|sed "s,^\~/,$HOME/,"` \
                   || export KDEHOME=$HOME/.kde
[ -z "$KDEROOTHOME" -a "$UID" == "0" ] && export KDEROOTHOME=$HOME/.kde
echo "$PATH" | grep -q "${KDEMAINDIR}bin" || export PATH=${KDEMAINDIR}bin:$PATH

# on autologin krootimage didn't run
if test -n "$KDM_AUTOLOGIN"; then # get rid of the ugly background as soon as possible
  if test -e /etc/opt/kde3/share/config/kdm/backgroundrc; then
    krootimage /etc/opt/kde3/share/config/kdm/backgroundrc
  else
    krootimage kdm/backgroundrc
  fi
fi

#
# Is this the first KDE 3 start with that KDEHOME ?
#
if [ -e $HOME/.kde2 -a ! -e $HOME/.skel/kdebase3 ]; then
#   [ "$USER" == "root" ] && xsetroot -cursor_name left_ptr -solid "#bd0000" \
#                         || xsetroot -cursor_name left_ptr -solid "#ACB29C"
   $KDEMAINDIR/bin/updatedialog
   S="$?"
   if [ "$S" == "0" -o "$S" == "1" ]; then
      if [ -e "$KDEHOME" -a ! -e "$HOME/.kde1" ]; then
         mv "$KDEHOME" "$HOME/.kde1"
      fi
      rm -rf "$HOME/.kde"
      if [ "$S" == "0" ]; then
	 mkdir -p "$HOME/.kde" "$HOME/Desktop/"
	 cd $HOME/.kde2/
	 tar cfp - --exclude=thumbnails --exclude=cache --exclude=socket-\* \
	           --exclude=tmp-\* * | tar xfv - -C "$KDEHOME"
	 for i in share/config/* ; do
	   sed -e 's,/opt/kde2/,/opt/kde3/,g' -e "s!$HOME/.kde2!$HOME/.kde!g" \
	          "$i" > "$HOME/.kde/$i"
	 done
	 sed -e 's,^Wallpaper=SuSE-Desktop_\(.*\).png,Wallpaper=SuSE-Desktop_\1.jpeg,' \
	          "share/config/kdesktoprc" > "$HOME/.kde/share/config/kdesktoprc"
	 cd -
	 [ "`du -ms $HOME/KDesktop/|awk '{ print $1 }'`" -lt 15 ] \
	   && cp -a $HOME/KDesktop/* $HOME/Desktop/ \
	   || mv    $HOME/KDesktop/* $HOME/Desktop/
         mkdir -p $HOME/.skel/
         touch $HOME/.skel/kdebase3
      fi
   fi
fi

if [ -r /etc/sysconfig/windowmanager ]; then
  # Do the user want the SuSE theme ?
  source /etc/sysconfig/windowmanager

  # Should we really enable FAM support for KDE ?
  export USE_FAM="$KDE_USE_FAM"

  # Should we use the fast malloc function from kdecore ?
  case $KDE_USE_FAST_MALLOC in
    yes|YES|1) KDE_MALLOC=1 ;;
  esac
else
  if [ -r /etc/rc.config ]; then
    # Do the user want the SuSE theme ?
    INSTALL_DESKTOP_EXTENSIONS=`bash -c "source /etc/rc.config && echo \\$INSTALL_DESKTOP_EXTENSIONS"`

    # Should we really enable FAM support for KDE ?
    USE_FAM=`bash -c "source /etc/rc.config && echo \\$KDE_USE_FAM"`
    export USE_FAM
  fi

  # Should we use the fast malloc function from kdecore ?
  KDE_USE_FAST_MALLOC=`bash -c "source /etc/rc.config && echo \\$KDE_USE_FAST_MALLOC"`
  case $KDE_USE_FAST_MALLOC in
    yes|YES|1) KDE_MALLOC=1 ;;
  esac
fi


#
# use optimized libs, if your CPU has the needed support
# (kdemultimedia package has some SSE optimized libs)
[ -z "$LD_HWCAP_MASK" ]    && export LD_HWCAP_MASK=0x20000000

#
# create SuSE defaults
#
if [ "$INSTALL_DESKTOP_EXTENSIONS" == "yes" ]; then
  if [ "$USER" == "root" ]; then
     if [ ! -e "$HOME/.skel/kdebase3" -a ! -e "$KDEHOME/share/config/kdeglobals" ]; then
        if [ -e "/opt/kde3/bin/startkde.theme.unitedlinux" ]; then
           . /opt/kde3/bin/startkde.theme.unitedlinux
           copy_default_root_ul "$KDEHOME"
           create_default_desktop_ul "$HOME/Desktop/"
        fi

        if [ -e "/opt/kde3/bin/startkde.theme" ]; then
           . /opt/kde3/bin/startkde.theme
        fi
        copy_default_root "$KDEHOME"
        mkdir -p $HOME/.skel/
        touch $HOME/.skel/kdebase3 $HOME/.skel/kdebase3.91
     fi
  else
     if [ ! -e "$HOME/.skel/kdebase3" -a ! -e "$KDEHOME/share/config/kdeglobals" ]; then
        if [ -e "/opt/kde3/bin/startkde.theme.unitedlinux" ]; then
           . /opt/kde3/bin/startkde.theme.unitedlinux
           copy_default_user_ul "$KDEHOME"
           create_default_desktop_ul "$HOME/Desktop/"
        fi

        if [ -e "/opt/kde3/bin/startkde.theme" ]; then
          . /opt/kde3/bin/startkde.theme
        fi
        copy_default_user "$KDEHOME"
        create_default_desktop "$HOME/Desktop/"
        mkdir -p $HOME/.skel/
        touch $HOME/.skel/kdebase3 $HOME/.skel/kdebase3.91
     fi
  fi
  if [ -e /opt/kde3/bin/startkde.update91 -a ! -e "$HOME/.skel/kdebase3.91" ]; then
     . /opt/kde3/bin/startkde.update91
     mkdir -p $HOME/.skel/
     touch $HOME/.skel/kdebase3.91
  fi
  for i in /opt/kde3/share/UnitedLinux/addon-scripts/*; do
    [ -r "$i" ] && \
     . "$i"
  done
fi

usr_odir=$HOME/.fonts/kde-override
usr_fdir=$HOME/.fonts

# Add any user-installed font directories to the X font path
kde_fontpaths=$usr_fdir/fontpaths
do_usr_fdir=1
do_usr_odir=1
if test -r "$kde_fontpaths" ; then
    savifs=$IFS
    IFS=$'\n'
    for fpath in `grep -v '^[   ]*#' < "$kde_fontpaths"` ; do
        if test -s "$fpath"/fonts.dir; then
            xset fp+ "$fpath"
            if test "$fpath" = "$usr_fdir"; then
                do_usr_fdir=0
            fi
            if test "$fpath" = "$usr_odir"; then
                do_usr_odir=0
            fi
        fi
    done
    IFS=$savifs
fi

if test -n "$KDEDIRS"; then
  kdedirs_first=`echo "$KDEDIRS"|sed -e 's/:.*//'`
  sys_odir=$kdedirs_first/share/fonts/override
  sys_fdir=$kdedirs_first/share/fonts
else
  sys_odir=$KDEDIR/share/fonts/override
  sys_fdir=$KDEDIR/share/fonts
fi

# We run mkfontdir on the user's font dirs (if we have permission) to pick
# up any new fonts they may have installed. If mkfontdir fails, we still
# add the user's dirs to the font path, as they might simply have been made
# read-only by the administrator, for whatever reason.

# Only do usr_fdir and usr_odir if they are *not* listed in fontpaths
test -d "$sys_odir" && xset +fp "$sys_odir"
test $do_usr_odir -eq 1 && test -d "$usr_odir" && (mkfontdir "$usr_odir" ; xset +fp "$usr_odir")
test $do_usr_fdir -eq 1 && test -d "$usr_fdir" && (mkfontdir "$usr_fdir" ; xset fp+ "$usr_fdir")
test -d "$sys_fdir" && xset fp+ "$sys_fdir"

# Ask X11 to rebuild its font list.
xset fp rehash

xsetroot -cursor_name left_ptr

#
# do we run in a prelinked system ?
#
if test -f /etc/sysconfig/prelink; then
. /etc/sysconfig/prelink
  if test "$USE_PRELINK" = "yes" ; then
     KDE_IS_PRELINKED=1
     export KDE_IS_PRELINKED
  else
     unset KDE_IS_PRELINKED
  fi
fi

#
# Do we have a special Gtk theming for our Qt widget theme ?
#
if [ ! -e $HOME/.no-qtrc-to-gtkrc-mapping ]; then
  [ -r $HOME/.qt/qtrc ] && \
  STYLE="`sed -n -e 's,^style=\(.*\),\1,p' $HOME/.qt/qtrc`"
  [ -z "$STYLE" ] && STYLE="keramik"
  export STYLE

  SUSE_VERSION="`cat /etc/SuSE-release | sed -n 's/VERSION = //p'`"

  if [[ "$SUSE_VERSION" > 8.2 ]] ; then
    # Defaults for SuSE 9.0
    GTK_SYSCONFDIR=/etc/opt/gnome
    GTK2_SYSCONFDIR=/etc/opt/gnome
    GTK_DATADIR=/opt/gnome/share
    GTK2_DATADIR=/opt/gnome/share
  else
    # Defaults for SuSE < 9.0
    # NOTE: SuSE 8.2 has broken theme location, fixed via YOU by symlinks.
    GTK_SYSCONFDIR=/etc
    GTK2_SYSCONFDIR=/etc
    GTK_DATADIR=/usr/share
    GTK2_DATADIR=/usr/share
  fi

  # Search for themes. If not exist, fall back to Geramik.
  GTK_THEME_RC="$GTK_DATADIR/themes/Geramik/gtk/gtkrc"
  for DIR in "$HOME/.themes" "$GTK_DATADIR/themes" ; do
    if [ -e "$DIR/$STYLE/gtk/gtkrc" ] ; then
      GTK_THEME_RC="$DIR/$STYLE/gtk/gtkrc"
      break
    fi
  done
  GTK2_THEME_RC="$GTK2_DATADIR/themes/Geramik/gtk-2.0/gtkrc"
  FOUND="0"
  for DIR in "$HOME/.themes" "$GTK2_DATADIR/themes" ; do
    if [ -e "$DIR/$STYLE/gtk-2.0/gtkrc" ] ; then
      GTK2_THEME_RC="$DIR/$STYLE/gtk-2.0/gtkrc"
      FOUND="1"
      break
    fi
  done
  # use general gtk-qt-engine, if nothing better was found
  if [ "$FOUND" == "0" -a -e "$DIR/Qt/gtk-2.0/gtkrc" ] ; then
    GTK2_THEME_RC="$DIR/Qt/gtk-2.0/gtkrc"
    break
  fi

  # GTK1
  # NOTE: ~/.gtkrc-kde is added later
  if [ "$GTK_RC_FILES" ]; then
    export GTK_RC_FILES="$GTK_RC_FILES:$GTK_THEME_RC:$HOME/.gtkrc-$STYLE"
  else
    export GTK_RC_FILES="$GTK_SYSCONFDIR/gtk/gtkrc:$GTK_THEME_RC:$HOME/.gtkrc-$STYLE"
  fi

  # GTK2
  # NOTE: ~/.gtkrc-2.0-kde is added later (in latest KDE only)
  if [ "$GTK2_RC_FILES" ]; then
    export GTK2_RC_FILES="$GTK2_RC_FILES:$GTK2_THEME_RC:$HOME/.gtkrc-2.0-$STYLE"
  else
    export GTK2_RC_FILES="$GTK2_SYSCONFDIR/gtk-2.0/gtkrc:$GTK2_THEME_RC:$HOME/.gtkrc-2.0-$STYLE"
  fi

fi

#
# setup and use needed font pathes
#
mkdir -p "$HOME/.fonts/kde-override"
xset +fp "$HOME/.fonts/kde-override"
xset fp+ "$HOME/.fonts"

#
# shutdown possible running dcopserver, which cause a login failure
# Link "tmp" and "socket" resource to directory in /tmp
# Creates a directory /tmp/kde-$USER and links $KDEHOME/tmp-$HOSTNAME to it.
dcopserver_shutdown
if [ -e "$KDEHOME/tmp-$HOSTNAME" -a ! -L "$KDEHOME/tmp-$HOSTNAME" ]; then
   rm -rf "/tmp/ksocket-$USER" "/tmp/kde-$USER"
   rm -rf "$KDEHOME/tmp-$HOSTNAME" "$KDEHOME/socket-$HOSTNAME"
   lnusertemp tmp >/dev/null
   lnusertemp socket >/dev/null
fi

# 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 -geometry 500x100 "Could not start kdeinit. Check your installation."
fi

#
# do we have a configured provider ?
#
if [ ! -e /${KDEMAINDIR}/share/autostart/kinternet.desktop -a -x /${KDEMAINDIR}/bin/kinternet ]; then
   /${KDEMAINDIR}/bin/kinternet --quiet --kicker &
fi

# 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 -geometry 500x100 "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^:^ ^'`
do
  for file in $prefix/*
  do
    if test -f $file
    then
       $file
    fi
  done
done

echo 'startkde: Done.'  1>&2

