#!/bin/sh
#
# ltsp-client-setup  Setup/Configure the LTSP client.
#
# chkconfig: 2345 00 65
# description: LTSP client initialization
# config: /usr/lib/ltsp/ltsp_config
# pidfile: /var/run/ltsp-client-setip.pid

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

# Source configuration.
SourceIfNotEmpty /etc/default/ltsp-client-setup

LOCKFILE=/var/lock/subsys/ltsp-client-setup
RETVAL=0

if [ -s /usr/lib/ltsp/ltsp_functions -a -f /etc/ltsp_chroot ]; then
	. /usr/lib/ltsp/ltsp_functions
	SourceIfNotEmpty /usr/lib/ltsp/ltsp_config
else
	exit 0
fi

load_modules()
{
	for module in $(env | grep '^MODULE_' | cut -d= -f2); do
		modprobe $module
	done
	is_yes "$POWER_BUTTON" && modprobe button
}

configure_localdev()
{
	if is_yes "$LOCALDEV"; then
		#[ -d /var/run/drives ] || mkdir /var/run/drives
		[ -d /tmp/drives ] || mkdir /tmp/drives
		/usr/sbin/lbuscd || true
    		/usr/sbin/ltspfsd -a || true
    		# cdrom devices are handled by the cdpingerponger
    		#/usr/sbin/cdpinger cdrom # default for usb cdroms
    		# and start one for every additional cdrom device
    		#if [ -L /dev/cdrom?* ];then
        	#	for CDDEV in $(ls /dev/cdrom?*); do
            			#/usr/sbin/cdpinger $(basename ${CDDEV})
        	#	done
    		#fi
    		# handle already plugged devices on login
    		#/usr/sbin/delayed_mounter
	fi
}

configure_console()
{
	[ -n "$CONSOLE_KEYMAP" ] && loadkeys "$CONSOLE_KEYMAP"
}

configure_swap()
{
	if [ "$USE_LOCAL_SWAP" = "Y" ]; then
    		# Enable local swap partition if found on local disk
		FST=`which fstyp 2>/dev/null` || FST=`which fstype 2>/dev/null` || FST=`which sfdisk 2>/dev/null` || FST=`which fdisk 2>/dev/null` || FST=`which file 2>/dev/null`
		case $(basename $FST) in
			fstyp)
				for part in `grep '[[:digit:]]$' /proc/partitions | sed -r -e 's/.*[[:blank:]]+([[:graph:]]+)$/\1/'`; do
					FSTYPE=`$FST /dev/$part 2>/dev/null`
					[ -n "$FSTYPE" -a "$FSTYPE" = "swap" ] swap_devices="$swap_devices /dev/$part"
				done
				;;
			fstype)
				for part in `grep '[[:digit:]]$' /proc/partitions | sed -r -e 's/.*[[:blank:]]+([[:graph:]]+)$/\1/'`; do
					FSTYPE=`$FST -d /dev/$part 2>/dev/null`
					[ -n "$FSTYPE" -a "$FSTYPE" = "swap" ] swap_devices="$swap_devices /dev/$part"
				done
				;;
			*fdisk)
				for part in `$FST -l 2>/dev/null | egrep '[[:blank:]]+Linux swap' | sed -r -e 's/^([[:graph:]]+).*/\1/'`; do
        				swap_devices="$swap_devices $part"
    				done
				;;
			file)
				for part in `grep '[[:digit:]]$' /proc/partitions | sed -r -e 's/.*[[:blank:]]+([[:graph:]]+)$/\1/'`; do
					FSTYPE=`$file -s /dev/$part`
					file -s /dev/$part 2>/dev/null | grep -q 'Linux.*swap' && swap_devices="$swap_devices /dev/$part"
				done
				;;
		esac
	fi
	if [ "$NBD_SWAP" = "Y" ]; then
    		SWAP_SERVER=${SWAP_SERVER:-"$SERVER"}
    		NBD_PORT=${NBD_PORT:-"9210"}
    		modprobe nbd
    		nbd-client $SWAP_SERVER $NBD_PORT /dev/nbd0 && swap_devices="$swap_devices /dev/nbd0"
	fi
	if [ "$ENCRYPT_SWAP" = "Y" ]; then
    		if [ -x /usr/sbin/cryptsetup ]; then
        		modprobe dm_crypt
    		else
        		echo "ERROR: ENCRYPT_SWAP=Y, but cryptsetup not found. disabling swap."
        		swap_devices=""
			ENCRYPT_SWAP="N"
    		fi
	fi
	num=0
	for device in $swap_devices ; do
    		swap="$device"
    		if [ "$ENCRYPT_SWAP" = "Y" ]; then
    			cryptsetup -d /dev/urandom create swap$num $swap && swap="/dev/mapper/swap$num"
    			num=$(($num+1))
    		fi
    		mkswap $swap
    		swapon $swap
	done
}

configure_resolver()
{
	hostname=$(hostname)
	if [ "(none)" = "$hostname" ] ; then
    		hostname="$(hostname)"
	else
    		echo $hostname > /etc/hostname
	fi
	echo "127.0.0.1 localhost" > /etc/hosts
	echo "127.0.0.2 $hostname" >> /etc/hosts
	echo "$SERVER server" >> /etc/hosts
	[ -s /etc/hosts.ltsp ] && cat /etc/hosts.ltsp >> /etc/hosts
	if [ -n "$DNS_SERVER" -a -n "$SEARCH_DOMAIN" ]; then
		echo "search $SEARCH_DOMAIN" > /etc/resolv.conf
		echo "nameserver $DNS_SERVER" >> /etc/resolv.conf
	fi
}

configure_network()
{
	return
}

configure_syslog()
{
	echo "*.* @${SYSLOG_HOST-$SERVER}" > /etc/syslog.conf
}

configure_fstab()
{
	echo "/dev/root	/	unionfs	defaults		0 0" > /etc/fstab
	echo "tmpfs	/tmp	tmpfs	defaults,nosuid,nodev	0 0" >> /etc/fstab
	mount /tmp
}

configure_x()
{
	if [ -z "$xserver_package" ]; then
		# set default xserver
		XSERVER_TYPE=$(basename $(readlink /usr/bin/X))
		XSERVER_TYPE=${XSERVER_TYPE:-$(basename $(readlink /usr/bin/X))}
	        case "$XSERVER_TYPE" in
			Xorg) xserver_config=/etc/X11/xorg.conf ;;
			XFree86) xserver_config=/etc/X11/XF86Config-4 ;;
			*) echo "WARNING: no known X server detected" >&2 ;;
		esac
	fi
	# set default configuration file
	case $xserver_package in
    		xserver-xfree86) xserver_config="/etc/X11/XF86Config-4" ;;
    		xserver-xorg) xserver_config="/etc/X11/xorg.conf" ;;
	esac
	if [ -n "$XF86CONFIG_FILE" ]; then
    		# User has specified a custom config
    		cp "$XF86CONFIG_FILE" "$xserver_config"
	else
    		# Autoconfigure
		if which x11createconfig 2>/dev/null 1>&2; then
			x11createconfig  > "$xserver_config"
		fi
    		# Handle overrides of specific parameters
    		if [ -n "$XSERVER" ] && [ "$XSERVER" != "auto" ]; then
			true
    		fi
    		X_USE_SYNC_RANGES=${X_USE_SYNC_RANGES:-Y}
    		if [ -n "$X_HORIZSYNC" -a -n "$X_VERTREFRESH" ]; then
			sed -i -r -e "s|^([[:blank:]]*HorizSync[[:blank:]]+).*$|\1$X_HORIZSYNC|" "$xserver_config"
			sed -i -r -e "s|^([[:blank:]]*VertRefresh[[:blank:]]+).*$|\1$X_VERTREFRESH|" "$xserver_config"
    		fi
    		# Color depth preseeding
    		[ -n "$X_COLOR_DEPTH" ] && sed -i -r -e "s|^([[:blank:]]*DefaultColorDepth[[:blank:]]+).*$|\1$X_COLOR_DEPTH|" "$xserver_config"
		# set compatbility for X_VIDEORAM with ltsp 4.x
		X_VIDEO_RAM=${X_VIDEO_RAM:-"$X_VIDEORAM"}
		# set video ram
    		[ -n "$X_VIDEO_RAM" ] && sed -i -r -e "s|^([[:blank:]]*VideoRam[[:blank:]]+).*$|\1$X_VIDEO_RAM|" "$xserver_config"
    		# Mouse preseeding options.  Use inputattach if available
		[ -n "$X_MOUSE_DEVICE" ]
		[ -n "$X_MOUSE_PROTOCOL" ]
    		[ -n "$X_MOUSE_EMULATE3BTN" ]
    		X_MODE=$(echo "$X_MODE_0 $X_MODE_1 $X_MODE_2" | sed -r 's/ +/, /g;s/, *$//g')
    		[ -n "$X_MODE" ]

    		if [ Y = "${USE_XFS}" ]; then
    			[ -z "$XFS_SERVER" ] && XFS_SERVER="$SERVER"
			[ -z "$XFS_PORT" ] && XFS_PORT=7100
			sed -i -r -e 's|^([[:blank:]]*FontPath[[:blank:]]+).*$|\1"tcp/'$XFS_SERVER':'$XFS_PORT'"|' "$xserver_config"
    		fi

    		# Make sure xkb values only get preseeded if the variables are actually set
		[ -n "$XKBMODEL" ] && echo "-model $XKBMODEL" >> /etc/X11/xinit/Xkbmap
		[ -n "$XKBLAYOUT" ] && echo "-layout $XKBLAYOUT" >> /etc/X11/xinit/Xkbmap
		[ -n "$XKBRULES" ] && echo "-rules $XKBRULES" >> /etc/X11/xinit/Xkbmap
		[ -n "$XKBVARIANT" ] && echo "-variant $XKBVARIANT" >> /etc/X11/xinit/Xkbmap
		if [ -n "$XKBOPTIONS" ]; then
		    for opt in $XKBOPTIONS; do
			echo "-option $opt" >> /etc/X11/xinit/Xkbmap
		    done
		fi
		[ -n "$XKBOPTION" ] && echo "-option $XKBOPTION" >> /etc/X11/xinit/Xkbmap
	fi
}

bind_unmounts()
{
	for dir in $temp_copy_dirs; do
		umount $dir
		rm -rf $tmpfs_dir/${dir#/}
	done
}

run_rcfiles()
{
	for rcfile in $(env | sort | awk -F= '$1 ~ /^RCFILE_/ { print $2 }'); do
	    [ -x "$rcfile" ] && "$rcfile" $@
	done
}

start()
{
	msg_starting $"Setting up LTSP client"
    	load_modules || true
    	configure_console || true
    	configure_network || true
    	configure_resolver || true
    	configure_swap || true
    	configure_syslog || true
    	configure_fstab || true
    	run_rcfiles || true
    	configure_x || true
    	configure_localdev ||true
	[ "$root_write_method" = "bind_mounts" ] && bind_unmounts
    	RETVAL=$?
	touch "$LOCKFILE"
    	return $RETVAL
}

stop()
{
	rm -f "$LOCKFILE"
	RETVAL=0
        return $RETVAL
}

status()
{
	if [ -f "$LOCKFILE" ]; then
		echo "This service was last time (re-)started at $(LANG=C LANGUAGE=C /bin/ls -l "$LOCKFILE" --full-time | tr -s ' ' | cut -f 6-10 -d' ')."
		echo "No other status information available for this package."
		echo "All this doesn't mean that there have not been perfomed any other (not init-forced) LTSP client changes since the given time."
	else
		echo "This service hasn't been started since stopped last time."
		echo "This does mean nothing at all (stopping the service doesn't unload the LTSP client)."
	fi
	RETVAL=$?
	return $RETVAL
}

case "$1" in
	start|restart|reload)
		start
		;;
	condrestart|condreload)
    		# Nothing to do on condrestart
		RETVAL=0
    		;;
	stop|condstop)
		stop
		;;
	status)
		status
		;;
	*)
		msg_usage "${0##*/} {start|stop|restart|reload|status|condrestart|condreload|condstop}"
		RETVAL=1
		;;
esac

exit $RETVAL
