#!/bin/bash

# override tool behaviour through distro-defaults
FLL_DISTRO_MODE="installed"
FLL_DISTRO_NAME="KANOTIX"
FLL_LIVE_USER="kanotix"
FLL_IMAGE_DIR="KANOTIX"
FLL_CDROM_INDEX="KANOTIX Manual"
FLL_CDROM_INDEX_ICON="html"
FLL_WALLPAPER_PREFIX="kanotix"

if [ -r /etc/default/distro ]; then
	source /etc/default/distro
fi

# don't ever start me on an installed system
[ ! "$FLL_DISTRO_MODE" = "live" ] && exit 0

umask 022

LANGUAGE="$(echo $LANG | cut -d\_ -f1)"

# Functions shamelessly copied from -autoconfig
stringinstring() {
	case "$2" in
		*$1*)
			return 0
			;;
	esac
	
	return 1
}

# Reread boot command line; echo last parameter's argument or return false.
getbootparam() {
	stringinstring " $1=" "$CMDLINE" || return 1
	result="${CMDLINE##*$1=}"
	result="${result%%[     ]*}"
	echo "$result"
	
	return 0
}

# Check boot commandline for specified option
checkbootparam() {
	stringinstring " $1" "$CMDLINE"
	return "$?"
}

# /etc/X11/Xsession.d/75dbus_dbus-launch
# needed for beryl/compiz

STARTDBUS=
DBUSLAUNCH=/usr/bin/dbus-launch

if grep -qs ^use-session-dbus "$OPTIONFILE"; then
	if [ -x "$DBUSLAUNCH" ]; then
		STARTDBUS=yes
	fi
fi

if [ -n "$STARTDBUS" ]; then
	DBUS=$($DBUSLAUNCH --exit-with-session)
	eval "$DBUS"
	export DBUS_SESSION_BUS_ADDRESS
fi 	 

# end /etc/X11/Xsession.d/75dbus_dbus-launch

[ -n "$KDEDIR" ] || KDEDIR="/usr"
export KDEDIR

[ -n "$HOSTNAME" ] || HOSTNAME="$(hostname)"
export HOSTNAME

[ -z "$USER" ] && USER="$(id -nu)"
export USER

[ -z "$HOME" -o "$HOME" = "/" ] && HOME="/home/$USER"
export HOME

# Set default cursor (artwiz)
xsetroot -cursor_name left_ptr

# add at least _one_ entry to xauth
# remove when updated nxclient is available

xauth add $DISPLAY  MIT-MAGIC-COOKIE-1  $(mcookie)

DONTCHANGE=""
[ -e $HOME/.kde/share/config/kdeglobals ] && DONTCHANGE="yes"

# Don't use this yet. We don't have TTF equivalents for all
# Fonts yet.
# QT_XFT=1
# export QT_XFT

# We need to source this so that the login screens get translated
[ -f /etc/profile ] && . /etc/profile

# debian's /etc/profile will only give a path with /sbin to root
PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/bin"
export PATH

# Read default language/keyboard/background image
[ -f /etc/sysconfig/knoppix ]  && . /etc/sysconfig/knoppix
[ -f /etc/sysconfig/i18n ]  && . /etc/sysconfig/i18n

if [ -n "$LANG" ]; then
	# Try to repair a KDE/locale bug
	LA="$LANG"
	L="${LANG%%@*}"
	C=$(awk '/^'"$LANG"'/{print $2;exit 0}' /etc/locale.gen 2>/dev/null)
	[ -n "$L" -a -n "$C" ] && LANG="$L.$C"
	LC_ALL="$LA"
	export LANG
fi

if [ -n "$LC_ALL" ]; then
	export LC_ALL
fi

[ -f /etc/sysconfig/keyboard ]  && . /etc/sysconfig/keyboard

# Read Desktop, currently kde, gnome, larswm and twm are supported in this script
[ -f /etc/sysconfig/desktop ]  && . /etc/sysconfig/desktop

# kde is the default
[ -z "$DESKTOP" ] && DESKTOP="kde"

# Copy profiles if not already present
# modified to pull entire /etc/skel and $HOME_PROF folder contents,
# depending on ramdisk space constraints

# Calculate size of /etc/skel and $HOME_PROF dirs
HOME_PROF=/usr/share/user-profile/profile
[ -d /usr/share/knoppix/profile ] && HOME_PROF=/usr/share/knoppix/profile
[ -d /usr/share/kanotix/profile ] && HOME_PROF=/usr/share/kanotix/profile

HOME_SIZE="$(( $(du --max-depth=0 $HOME_PROF | awk '{ print $1 }') + $(du --max-depth=0 /etc/skel | awk '{ print $1 }') ))"

# Calculate free space on partition containing /home dir
FREESPACE="$(df -k "$HOME" | awk '/^\/|^rootfs/{print $4}')"

if [ "$FREESPACE" -gt "$HOME_SIZE" ]; then
	# if there's space, copy entire /etc/skel and $HOME_PROF
	rsync -Ha --ignore-existing /etc/skel/ $HOME 2>/dev/null
	[ "$USER" = "$FLL_LIVE_USER" ] && rsync -Ha --ignore-existing $HOME_PROF/ "$HOME/" 2>/dev/null
else
	# if there's not enough space, copy important dir only
	# XXX - not sure how "important" .klik and .zAppRun are...- bg
	rsync -Ha --ignore-existing /etc/skel/{.Xdefaults,.bashrc,.qt,.gtk*} $HOME/ 2>/dev/null
	[ "$USER" = "$FLL_LIVE_USER" ] && rsync -Ha --ignore-existing $HOME_PROF/{.Xdefaults,.bashrc,.qt,.kde,.klik,.zAppRun} "$HOME/" 2>/dev/null
fi

# add aliases for sudo and su
grep alias\ su /home/$FLL_LIVE_USER/.bashrc > /dev/null || echo "alias su=\"sudo su\"" >> /home/$FLL_LIVE_USER/.bashrc
grep alias\ sux /home/$FLL_LIVE_USER/.bashrc > /dev/null || echo "alias sux=\"sudo sux\"" >> /home/$FLL_LIVE_USER/.bashrc

# configure kdesu to use sudo for the live user
if kde-config && [ ! -r /home/$FLL_LIVE_USER/.kde/share/config/kdesurc ] ; then
	mkdir -p /home/$FLL_LIVE_USER/.kde/share/config/
	echo "[super-user-command]" > /home/$FLL_LIVE_USER/.kde/share/config/kdesurc
	echo "super-user-command=sudo" >> /home/$FLL_LIVE_USER/.kde/share/config/kdesurc
fi

# Share Mozilla plugins with Firefox
if [ -x /usr/bin/mozilla-firefox ]; then
	if [ -e $HOME/.mozilla ]; then
		mkdir -p $HOME/.mozilla/plugins $HOME/.firefox
		[ -e $HOME/.firefox/plugins ] || ln -s ../.mozilla/plugins $HOME/.firefox/plugins
	fi
fi
	    
if [ -n "$LANGUAGE" ]; then
	# Set mozilla's preferred language
	for f in `ls -1 $HOME/.mozilla/*/*/prefs.js 2>/dev/null`; do
		echo 'user_pref("intl.accept_languages", "'"$LANGUAGE"', en");' >>"$f"
		
		case "$LANG" in
			de*|at*|ch*)
				echo 'user_pref("general.useragent.contentlocale", "AT");' >>"$f"
				echo 'user_pref("general.useragent.locale", "de-AT");' >>"$f" ;;
		esac
		# Else leave default language
done

for f in `ls -1 $HOME/.mozilla/*/*/chrome/chrome.rdf.$LANGUAGE 2>/dev/null`; do
	mv -f "$f" "${f%%.${LANGUAGE}}"
done

fi

playsound(){
	# Play sound if soundcore module present (checking /dev/sndstat is unreliable)
	OGGPLAY=/usr/bin/ogg123
	PLAY=/usr/bin/wavp
	[ -x "$PLAY" ] || PLAY=/usr/bin/play-sample
	[ -x "$PLAY" ] || PLAY=/usr/bin/play

	if [ -x "$OGGPLAY" -a -f /usr/share/sounds/startup.ogg ]; then
		case "$(lsmod)" in 
			*sound*)
				{ $OGGPLAY -q -p 64 /usr/share/sounds/startup.ogg >/dev/null 2>&1 & }
				sleep 1
				;;
		esac
	elif [ -f /usr/share/sounds/startup.wav -a -x "$PLAY" ]; then
		case "$(lsmod)" in
			*sound*)
				{ $PLAY /usr/share/sounds/startup.wav >/dev/null 2>&1 & }
				sleep 2
				;;
			esac
	fi
}

startkde() {
	# Play sound

	CMDLINE=$(cat /proc/cmdline) # FIXME!

	if [ -z "$DONTCHANGE" ]; then
		# No persistent homedir, copy everything
		rsync -Ha --ignore-existing /etc/skel/{.kde*,Desktop} $HOME/ 2>/dev/null
		[ "$USER" = "$FLL_LIVE_USER" ] && rsync -Ha --ignore-existing $HOME_PROF/{.kde*,Desktop} $HOME/ 2>/dev/null
	else
		# Only regenerate the config and Desktop files if missing
		mkdir -p $HOME/.kde/share $HOME/Desktop
		rsync -Ha --ignore-existing /etc/skel/.kde/share/* $HOME/.kde/share/ 2>/dev/null
		[ "$USER" = "$FLL_LIVE_USER" ] && rsync -Ha --ignore-existing $HOME_PROF/.kde/share/* $HOME/.kde/share/ 2>/dev/null
		rsync -Ha --ignore-existing /etc/skel/Desktop/* $HOME/Desktop/ 2>/dev/null
		[ "$USER" = "$FLL_LIVE_USER" ] && rsync -Ha --ignore-existing $HOME_PROF/Desktop/* $HOME/Desktop/ 2>/dev/null
		rm -f $HOME/.kde/Autostart/sorticons.desktop
	fi

	# Check for /index.html (_en), or KNOPPIX/index.html (_en) on this CD
	if [ -e /cdrom/index.html ]; then
		INDEXFILE="/cdrom/index.html"
	else
		for i in index ${FLL_IMAGE_DIR}/index; do
			INDEXFILEDE="/cdrom/${i}.html"
			INDEXFILEEN="/cdrom/${i}_en.html"
			[ -e "$INDEXFILEEN" ] && INDEXFILE="$INDEXFILEEN" && [ "$LANGUAGE" != "de" ] && break
			[ -e "$INDEXFILEDE" ] && INDEXFILE="$INDEXFILEDE" && [ "$LANGUAGE"  = "de" ] && break
		done
	fi

	if [ -e "$INDEXFILE" ]; then
		cat >> $HOME/Desktop/$FLL_DISTRO_NAME.desktop <<EOF
[Desktop Entry]
Name=$FLL_CDROM_INDEX
# Exec=kfmclient openProfile webbrowsing $INDEXFILE
Exec=konqueror --geometry 950x700+35+20 file:$INDEXFILE
Type=Application
Icon=$FLL_CDROM_INDEX_ICON
Terminal=0
EOF
		if ! checkbootparam "nointro"; then
			mkdir -p $HOME/.kde/Autostart
			ln $HOME/Desktop/$FLL_DISTRO_NAME.desktop $HOME/.kde/Autostart/showindex.desktop
		fi
	fi

	# LinuxTag
	if [ -d /cdrom/LinuxTag ]; then
		ln -sf /cdrom/LinuxTag "$HOME/Desktop/"
	fi

	# Beryl
	rm -f $HOME/.kde/Autostart/beryl.desktop
	
	if checkbootparam "beryl" && [ -x /usr/bin/beryl-manager ]; then
		mkdir -p $HOME/.kde/Autostart
		echo "[Desktop Entry]
Encoding=UTF-8
Exec=beryl-manager
GenericName[de_DE]=
StartupNotify=false
Terminal=false
TerminalOptions=
Type=Application
X-KDE-autostart-after=kdesktop" > $HOME/.kde/Autostart/beryl.desktop
		fi

	# Compiz
	rm -f $HOME/.kde/Autostart/compiz.desktop

	if checkbootparam "compiz" && [ -x /usr/bin/compiz ]; then
		mkdir -p $HOME/.kde/Autostart
		echo "[Desktop Entry]
Encoding=UTF-8
Exec=compiz --replace
GenericName[de_DE]=
StartupNotify=false
Terminal=false
TerminalOptions=
Type=Application
X-KDE-autostart-after=kdesktop" > $HOME/.kde/Autostart/compiz.desktop
	fi

	# Setup language/keyboard
	[ -d $HOME/.kde/share/config ] || mkdir -p $HOME/.kde/share/config
	
	if [ -z "$DONTCHANGE" ]; then
		touch $HOME/.kde/share/config/kdeglobals
		rm -f $HOME/.kde/share/config/kdeglobals.tmp
		
		sed -e 's/^Charset=.*$/Charset='"$CHARSET"'/' \
		    -e 's/^Country=.*$/Country='"$COUNTRY"'/' \
		    -e 's/^Language=.*$/Language='"$LANGUAGE"'/' \
		    $HOME/.kde/share/config/kdeglobals > $HOME/.kde/share/config/kdeglobals.tmp
		\mv -f $HOME/.kde/share/config/kdeglobals.tmp $HOME/.kde/share/config/kdeglobals

		if [ -z "$BACKGROUND" -o ! -e "$BACKGROUND" ]; then
			for i in png jpg gif; do
				BACKGROUND=usr/share/wallpapers/$FLL_WALLPAPER_PREFIX.$i
				[ -e "$BACKGROUND" ] && break
			done
		fi

		sed -e 's|Wallpaper=.*$|Wallpaper='"$BACKGROUND"'|g' \
		    $HOME/.kde/share/config/kdesktoprc > $HOME/.kde/share/config/kdesktoprc.tmp
		mv -f $HOME/.kde/share/config/kdesktoprc.tmp $HOME/.kde/share/config/kdesktoprc
		touch -r /etc/skel/.kde/share/config/kdeglobals $HOME/.kde/share/config/kdeglobals 2>/dev/null
		touch $HOME/.kde/share/config/kxkbrc
		rm -f $HOME/.kde/share/config/kxkbrc.tmp

		if [ -n "$FLL_KDEKEYBOARDS" ]; then
			sed -e 's/^LayoutList=.*$/LayoutList='"$FLL_KDEKEYBOARDS"'/' \
			    $HOME/.kde/share/config/kxkbrc > $HOME/.kde/share/config/kxkbrc.tmp	
		else
			sed -e 's/^Layout=.*$/Layout='"$KDEKEYBOARD"'/' \
			    -e 's/^Additional=.*$/Additional='"$KDEKEYBOARDS"'/' \
			    $HOME/.kde/share/config/kxkbrc > $HOME/.kde/share/config/kxkbrc.tmp
		fi
		mv -f $HOME/.kde/share/config/kxkbrc.tmp $HOME/.kde/share/config/kxkbrc
		touch -r /etc/skel/.kde/share/config/kxkbrc $HOME/.kde/share/config/kxkbrc 2>/dev/null

		# Check for custom splashscreen in /cdrom/KNOPPIX
		if [ -d /cdrom/${FLL_IMAGE_DIR}/ksplash ]; then
			[ -d $HOME/.kde/share/apps ] || mkdir -p $HOME/.kde/share/apps
			ln -s /cdrom/${FLL_IMAGE_DIR}/ksplash $HOME/.kde/share/apps/
		fi
	fi

	# Start KDE3
	echo "kde_restart" >/etc/sysconfig/xsession-commands
	export XDM_MANAGED="/etc/sysconfig/xsession-commands,maysd,mayfn,sched,method=classic"

	# This is /usr/bin/startkde

	# 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

	# Check if a KDE session already is running
	if kcheckrunning >/dev/null 2>&1; then
		echo "KDE seems to be already running on this display."
		xmessage -geometry 500x100 "KDE seems to be already running on this display." > /dev/null 2>/dev/null
		exit 1
	fi

	# we have to unset this for Darwin since it will screw up KDE's dynamic-loading
	unset DYLD_FORCE_FLAT_NAMESPACE

	# in case we have been started with full pathname spec without being in PATH
	bindir=`echo "$0" | sed -n 's,^\(/.*\)/[^/][^/]*$,\1,p'`
	if [ -n "$bindir" ]; then
		case $PATH in
			$bindir|$bindir:*|*:$bindir|*:$bindir:*)
				;;
			*)
				PATH=$bindir:$PATH
				export PATH
				;;
		esac
	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 takes control of the rest of the startup sequence
	
	# The user's personal KDE directory is usually ~/.kde, but this setting
	# may be overridden by setting KDEHOME.

	kdehome=$HOME/.kde
	test -n "$KDEHOME" && kdehome=`echo "$KDEHOME"|sed "s,^~/,$HOME/,"`

	# XCursor mouse theme needs to be applied here to work even for kded or ksmserver
	if test -n "$kcminputrc_mouse_cursortheme" -o -n "$kcminputrc_mouse_cursorsize" ; then
		kapplymousetheme "$kcminputrc_mouse_cursortheme" "$kcminputrc_mouse_cursorsize"
		
		if test $? -eq 10; then
			export XCURSOR_THEME=default
		elif test -n "$kcminputrc_mouse_cursortheme"; then
			export XCURSOR_THEME="$kcminputrc_mouse_cursortheme"
		fi
	
		if test -n "$kcminputrc_mouse_cursorsize"; then
			export XCURSOR_SIZE="$kcminputrc_mouse_cursorsize"
		fi
	fi

	if test "$kcmrandrrc_display_applyonstartup" = "true"; then
		# 4 screens is hopefully enough
		for scrn in 0 1 2 3; do
			args=
			width="\$kcmrandrrc_screen${scrn}_width" ; eval "width=$width"
			height="\$kcmrandrrc_screen${scrn}_height" ; eval "height=$height"
	
			if test -n "${width}" -a -n "${height}"; then
				args="$args -s ${width}x${height}"
			fi
	
			refresh="\$kcmrandrrc_screen${scrn}_refresh" ; eval "refresh=$refresh"
			if test -n "${refresh}"; then
				args="$args -r ${refresh}"
			fi

			rotation="\$kcmrandrrc_screen${scrn}_rotation" ; eval "rotation=$rotation"
			if test -n "${rotation}"; then
				case "${rotation}" in
					0)
						args="$args -o 0"
						;;
					90)
						args="$args -o 1"
						;;
					180)
						args="$args -o 2"
						;;
					270)
						args="$args -o 3"
						;;
				esac
			fi
	
			reflectx="\$kcmrandrrc_screen${scrn}_reflectx" ; eval "reflectx=$reflectx"
			if test "${refrectx}" = "true"; then
				args="$args -x"
			fi
		
			reflecty="\$kcmrandrrc_screen${scrn}_reflecty" ; eval "reflecty=$reflecty"
			if test "${refrecty}" = "true"; then
				args="$args -y"
			fi
		
			if test -n "$args"; then
				xrandr $args
			fi
		done
	fi

	# Source scripts found in <localprefix>/env/*.sh and <prefixes>/env/*.sh
	# (where <localprefix> is $KDEHOME or ~/.kde, and <prefixes> is where KDE is installed)
	#
	# This is where you can define environment variables that will be available to
	# all KDE programs, so this is where you can run agents using e.g. eval `ssh-agent`
	# or eval `gpg-agent --daemon`.
	# Note: if you do that, you should also put "ssh-agent -k" as a shutdown script
	#
	# (see end of this file).
	# For anything else (that doesn't set env vars, or that needs a window manager),
	# better use the Autostart folder.
	
	exepath=`kde-config --path exe | tr : '\n'`
	
	for prefix in `echo "$exepath" | sed -n -e 's,/bin[^/]*/,/env/,p'`; do
		for file in "$prefix"*.sh; do
			test -r "$file" && . "$file"
		done
	done

	# 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.
	#
	# If the user has overwritten fonts, the cursor font may be different now
	# so don't move this up.
	#
	xsetroot -cursor_name left_ptr

	# 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
	case "$ksplashrc_ksplash_theme" in 
		None)
			;; # nothing
		Simple)
			ksplashsimple 
			;;
		*)
			ksplash --nodcop
			;;
	esac

	# certain features such as Konqueror preloading work only with full KDE running
	KDE_FULL_SESSION=true
	export KDE_FULL_SESSION

	# We set LD_BIND_NOW to increase the efficiency of kdeinit.
	# kdeinit unsets this variable before loading applications.
	LD_BIND_NOW=true kdeinit --new-startup +kcminit_startup
	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

	# finally, give the session control to the session manager
	# see kdebase/ksmserver for the description of the rest of the startup sequence
	# 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

	# wait if there's any crashhandler shown
	while dcop | grep -q ^drkonqi- ; do
		sleep 5
	done

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

	# Clean up
	kdeinit_shutdown
	dcopserver_shutdown --wait
	artsshell -q terminate

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

	# Run scripts found in $KDEDIRS/shutdown
	for prefix in `echo "$exepath" | sed -n -e 's,/bin[^/]*/,/shutdown/,p'`; do
		for file in `ls "$prefix" 2> /dev/null | egrep -v '(~|\.bak)$'`; do
			test -x "$prefix$file" && "$prefix$file"
		done
	done

	echo 'startkde: Done.'  1>&2

	# EOF /usr/bin/startkde
	killall kdeinit 2>/dev/null
	exit 0
}
# End startkde

# starttwm: This is also the error fallback windowmanager. It should display
# an error message if it was started as such.
# Paraeters: "reasoncode" "reasoncode-specific description"
starttwm() {
	XTERM=x-terminal-emulator
	$XTERM -geometry +0-0 -T Shell &

	MESSAGE=""
	if [ -n "$1" ]; then
		case "$1" in
			lowmem)
				case "$LANG" in
					de*|at*|ch*) MESSAGE="
Nicht genug Speicher zum Start von $DESKTOP!
(Mindestens $2 MB benötigt.)

Starte stattdessen den TWM Windowmanager.
Achtung: Nicht alle Programme im linke-
Maustaste-Menü werden funktionieren!
"
						;;
					es*)
						MESSAGE="
No hay suficiente memoria para arrancar $DESKTOP!
(Se necesitan al menos $2 MB.)

Usando el gestor de ventanas TWM en su lugar.
Aviso: ¡No todos los programas en
el menú que aparece al pulsar el botón izquierdo
del ratón funcionarán aquí!
"
						;;
					*) 
    						MESSAGE="
Not enough memory to start $DESKTOP!
(At least $2 MB required.)

Using TWM windowmanager instead.
Caution: Not all programs in
the left-Mousebutton-Menu will
work here!
"
						;;
				esac
				;;
			invalidwm)
				case "$LANG" in
					de*|at*|ch*)
						MESSAGE="
Desktop-Manager '$DESKTOP' wird nicht unterstützt!

Starte stattdessen den TWM Windowmanager.
Achtung: Nicht alle Programme im linke-
Maustaste-Menü werden funktionieren!
"
						;;
					es*)
						MESSAGE="
El gestor de ventanas '$DESKTOP' no esta soportado!

Usando el gestor de ventanas TWM en su lugar.
Aviso: ¡No todos los programas en
el menú que aparece al pulsar el botón izquierdo
del ratón funcionarán aquí!
"
						;;
					*)
						MESSAGE="
Desktop manager '$DESKTOP' is not supported!

Using TWM windowmanager instead.
Caution: Not all programs in
the left-Mousebutton-Menu will
work here!
"
						;;
				esac
				;;
		esac
	fi

	if [ -n "$MESSAGE" ]; then
		( xmessage -geometry -0+0 "
$MESSAGE
"
) &
		sleep 4
	fi

	playsound
	exec twm
}

startgnome() {
	type gnome-session >/dev/null 2>&1 || starttwm
	rsync -Ha --ignore-existing /etc/skel/{.gnome*,.gtk*,.metacity*,GNUstep,.sawfish,.nautilus,Nautilus} $HOME/ 2>/dev/null

	[ "$USER" = "$FLL_LIVE_USER" ] && rsync -Ha --ignore-existing $HOME_PROF/{.gnome*,GNUstep,.sawfish,.nautilus,Nautilus} $HOME/ 2>/dev/null

	playsound

	# nautilus2 cannot handle KDE icons correctly, so we have to remove them to avoid confusion
	find $HOME/Desktop -type f -size -2k -maxdepth 1 | while read f; do grep -qi '^\[.*Desktop Entry.*\]' "$f" && rm -f "$f"; done 2>/dev/null

	# Remove old .gnome-desktop
	mv -f .gnome-desktop .gnome-desktop.removed 2>/dev/null

	# Nautilus2 and others seem to depend on XFT
	GDK_USE_XFT=1 exec gnome-session
}

startlarswm() {
	[ -e "$HOME"/.larswmrc ] || rsync -Ha --ignore-existing /etc/skel/.larswmrc $HOME/ 2>/dev/null
	playsound
	exec larswm
}

startwindowmaker() {
	# Create automatic Desktop icons

	playsound
	GDK_USE_XFT=1 exec wmaker
}

starticewm() {
	playsound
	GDK_USE_XFT=1 exec icewm
}

startfluxbox() {
	playsound
	GDK_USE_XFT=1 exec fluxbox
}

startenlightenment() {
	playsound
	GDK_USE_XFT=1 exec enlightenment
}

startxfce() {
	playsound

	GDK_USE_XFT=1
	export GDK_USE_XFT

	[ -e $HOME/.xfce ] || mkdir $HOME/.xfce
	XFWM=xfwm

	exec $XFWM
}

startxfce4() {
	playsound

	GDK_USE_XFT=1
	export GDK_USE_XFT

	# XFCE4 setup
	if [ ! -e $HOME/.xfce4 ]; then
		rsync -Ha --ignore-existing /etc/skel/.xf* $HOME_PROF/.xf* $HOME/ 2>/dev/null
	fi
	exec /etc/xdg/xfce4/xinitrc 
}

startkiosk() {
	playsound
	GDK_USE_XFT=1 

	CMDLINE=$(cat /proc/cmdline) # FIXME!

	url=$(getbootparam url)

	cat <<EOF > $HOME/kiosk.html
<html>
<head>
<script language="javascript">
<!--
function StartKiosk(){
window.open("$url","","fullscreen,toolbar=yes,scrollbars=yes");
timeoutID=setTimeout("CloseLauncher()", 100);
}
function CloseLauncher(){
window.close();
}
-->
</script>
</head>
<body onLoad="StartKiosk()">
</body>
</html>
EOF

	echo 'user_pref("privacy.popups.first_popup", false);' >> $HOME/.mozilla/*/ujixazk6.slt/prefs.js
	echo 'user_pref("dom.allow_scripts_to_close_windows", true);' >> $HOME/.mozilla/*/ujixazk6.slt/prefs.js
	echo 'user_pref("browser.toolbars.showbutton.print", false);' >> $HOME/.mozilla/*/ujixazk6.slt/prefs.js

	while [ "$DESKTOP" = "kiosk" -o "$DESKTOP" = "KIOSK" ]; do
		mozilla $HOME/kiosk.html
		[ -f /etc/sysconfig/desktop ]  && . /etc/sysconfig/desktop
	done
}

startrdp() {
	CMDLINE=$(cat /proc/cmdline) # FIXME!

	rdp_host=$(getbootparam rdp_host)
  
	#start some window manager
	kwin &

	# start rdesktop
	rdesktop "$rdp_host" || xmessage "Could not connect to server $rdp_host."
}

startnx() {
	CMDLINE=$(cat /proc/cmdline) # FIXME!
  
	# Create .nx config ...
	mkdir -p $HOME/.nx/config

	nx_ssl=$(getbootparam nx_ssl)

	nx_desktop=$(getbootparam nx_desktop)
	nx_link_speed=$(getbootparam nx_link_speed)
	nx_resolution=$(getbootparam nx_resolution)
	nx_server_host=$(getbootparam nx_server_host)
	nx_server_port=$(getbootparam nx_server_port)
	nx_session=$(getbootparam nx_session)
  
	nx_auth=$(getbootparam nx_auth)
	nx_password=$(getbootparam nx_password)
	nx_user=$(getbootparam nx_user)

	# FIXME for 1.4.0
	cat <<EOF > $HOME/.nx/config/termserv.conf
<!DOCTYPE KSettings>
<KSettings application="nxclient" version="1.3" >
<group name="Advanced" >
<option key="Enable SSL encryption" value="${nx_ssl:-true}" />
</group>
<group name="General" >
<option key="Desktop" value="${nx_desktop:-KDE}" />
<option key="Link speed" value="${nx_link_speed:-modem}" />
<option key="Resolution" value="${nx_resolution:-fullscreen}" />
<option key="Resolution height" value="600" />
<option key="Resolution width" value="800" />
<option key="Server host" value="${nx_server_host:-localhost}" />
<option key="Server port" value="${nx_server_port:-22}" />
<option key="Session" value="${nx_session:-Unix}" />
</group>
<group name="Login" >
<option key="Auth" value="${nx_auth}" />
<option key="Password" value="${nx_password}" />
<option key="User" value="${nx_user:-$FLL_LIVE_USER}" />
</group>
<group name="VNC Session" >
<option key="Password" value="" />
</group>
<group name="Windows Session" >
<option key="Password" value="" />
</group>
</KSettings>
EOF

	cat <<EOF > $HOME/.nx/config/nxclient.conf
<!DOCTYPE NXClientSettings>
<NXClientSettings application="nxclient" version="1.3" >
<group name="General" >
<option key="Personal NX dir" value="/home/$FLL_LIVE_USER/.nx" />
</group>
</NXClientSettings>
EOF

	#start some window manager
	kwin &

	# start nxclient and do that in an endless loop
	while true; do
		nxclient --session "termserv"
		sleep 2
	done
}

# Check for sufficient Real Memory for starting KDE or GNOME
# (We don't want to end in a swap-a-lot loop.)
REALMEM="$(awk '/MemTotal/{print $2}' /proc/meminfo)"
FREEMEM="$(awk 'BEGIN{m=0};/MemFree|Cached|SwapFree/{m+=$2};END{print m}' /proc/meminfo)"

if [ "$REALMEM" -lt 25000 ]; then
	starttwm
else
	case "$DESKTOP" in
		kde|KDE)
			[ "$FREEMEM" -ge "60000" ] && startkde			|| starttwm lowmem 82
			;;
		gnome|GNOME)
			[ "$FREEMEM" -ge "45000" ] && startgnome		|| starttwm lowmem 67
			;;
		larswm|LARSWM)
			[ "$FREEMEM" -ge "35000" ] && startlarswm		|| starttwm lowmem 64
			;;
		enlightenment|ENLIGHTENMENT)
			[ "$FREEMEM" -ge "35000" ] && startenlightenment	|| starttwm lowmem 64
			;;
		fluxbox|FLUXBOX)
			[ "$FREEMEM" -ge "35000" ] && startfluxbox		|| starttwm lowmem 64
			;;
		xfce|xfce3|XFCE|XFCE3)
			[ "$FREEMEM" -ge "35000" ] && startxfce			|| starttwm lowmem 64
			;;
		xfce4|XFCE4)
			[ "$FREEMEM" -ge "35000" ] && startxfce4		|| starttwm lowmem 64
			;;
		windowmaker|wmaker|WINDOWMAKER|WMAKER)
			[ "$FREEMEM" -ge "35000" ] && startwindowmaker		|| starttwm lowmem 64
			;;
		icewm|ICEWM)
			[ "$FREEMEM" -ge "35000" ] && starticewm		|| starttwm lowmem 64
			;;
		nx|NX)
			startnx
			;;
		kiosk|kiosk)
			startkiosk
			;;
		rdp|rdp)
			startrdp
			;;
	        twm|TWM)
			starttwm
			;;
		*)
			starttwm invalidwm
			;;
	esac
fi

