#!/bin/sh
# /etc/init.d/rcS - Initial boot script for SliTaz GNU/Linux. 
# Config file is : /etc/rcS.conf
#
# rcS is the main initialization script used to check fs, mount, clean,
# run scripts and start daemons.
#
. /etc/init.d/rc.functions
. /etc/rcS.conf

# Boot time.
bootdate=`date +%s`

if [ "$1" != "logged" ]; then # logged

echo "Processing /etc/init.d/rcS..."

# Mount /proc.
echo -n "Mounting proc filesystem..."
/bin/mount proc
status

# Parse cmdline args for earlier boot options. All other boot options
# are in /etc/init./bootopts.sh.
echo -n "Searching for early boot options..."
for opt in `cat /proc/cmdline`
do
	case $opt in
		fastbootx|fbx)
			export FAST_BOOT_X="yes" ;;
		cdrom=*)
			export CDROM=${opt#cdrom=} ;;
		modprobe=*)
			export MODPROBE="yes" ;;
		config=*)
			export CONFIG=${opt#config=} ;;
		*)
			continue ;;
	esac
done
status

# Start Udev to populate /dev and handle hotplug events
if [ "$UDEV" = "yes" ]; then
	echo -n "Starting udev daemon..."
	/sbin/udevd --daemon
	status
	echo -n "Udevadm requesting events from the Kernel..."
	udevadm trigger
	status
	echo -n "Udevadm waiting for the event queue to finish..."
	udevadm settle
	status
	echo "/sbin/udevd" > /proc/sys/kernel/hotplug
fi

# Before mounting filesystems we check fs specified in the file
# /etc/rcS.conf and variable $CHECK_FS.
if [ -n "$CHECK_FS" ]; then
	mount -o remount,ro /
	for i in $CHECK_FS
	do
		echo "Checking filesystem on : $i"
		/sbin/e2fsck -p $i
	done
fi

# Remount rootfs rw.
echo "Remounting rootfs read/write..."
/bin/mount -o remount,rw /

# Mount filesystems in /etc/fstab.
echo "Mounting filesystems in fstab..."
/bin/mount -a

# Store boot messages to log files.
/bin/dmesg > /var/log/dmesg.log &
vcsa2txt < /dev/vcsa1 | awk 'BEGIN {s=0} /^Processing|^.witching/ {s=1} { if (s) print }' >/var/log/boot.log
script -a -q -c '/etc/init.d/rcS logged' /var/log/boot.log

else # logged

# Clean up the system.
if [ "$CLEAN_UP_SYSTEM" = "yes" ]; then
	echo -n "Cleaning up the system..."
	find /var/run -name "*.pid" -type f | xargs /bin/rm -f
	/bin/rm -rf /tmp /var/run/dbus/* /var/run/hald/pid /var/lock/*
	/bin/mkdir -p /tmp && /bin/chmod 1777 /tmp
	status
else
	echo "System clean up is disabled in /etc/rcS.conf..."
	echo -n "Keeping all tmp and pid files..."
	status
fi

# Set up tmp X11 and ICE dir.
echo -n "Setting up tmp X11 and ICE unix dir..."
/bin/mkdir -p /tmp/.X11-unix /tmp/.ICE-unix
/bin/chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix
status

# Fast boot into X for HD install or custom Live system. We need 
# keymap settings since Xvesa dumps the console mapping and a correct
# slim configuration for screen resolution. DBUS and HAL must also start
# before X session (manual login or autologin) to have devices in PCmanFM.
if [ "$FAST_BOOT_X" = "yes" ]; then
	/etc/init.d/i18n.sh
	/etc/init.d/dbus start
	/etc/init.d/hald start
	/etc/init.d/slim start &
fi

# Create /dev/cdrom if needed (symlink does not exist on LiveCD).
# Also add /dev/cdrom to fstab if entry does not exist.
if [ -n "$CDROM" ]; then
	DRIVE_NAME=${CDROM#/dev/}
else
	DRIVE_NAME=`cat /proc/sys/dev/cdrom/info | grep "drive name" | cut -f 3`
fi
if [ -n "$DRIVE_NAME" -a ! "`readlink /dev/cdrom`" ]; then
	echo -n "Creating symlink : /dev/cdrom..."
	ln -s /dev/$DRIVE_NAME /dev/cdrom
	ln -s /dev/$DRIVE_NAME /dev/dvd
	status
fi
if ! grep -q "/dev/cdrom" /etc/fstab; then
	echo -n "Adding /dev/cdrom  to fstab..."
	echo '/dev/cdrom      /media/cdrom iso9660 user,ro,noauto       0       0' \
		>> /etc/fstab
	status
fi
# Chmod hack on each boot for Asunder and burnbox. Allowing all users
# to burn/rip CD/DVD.
if [ -n "$DRIVE_NAME" -a "`readlink /dev/cdrom`" ]; then
	echo -n "Chmoding cdrom device..."
	chmod 0666 /dev/cdrom
	chmod 0666 /dev/dvd
	chmod 0666 /dev/$DRIVE_NAME
	status
fi

# Handle kernel cmdline parameter modprobe=<module_list> 
MODULES=$(sed '/modprobe=/!d;s/.* modprobe=\([^ ]*\).*/\1/;s/,/ /g' /proc/cmdline)
for i in $MODULES; do
	echo -n "Loading kernel module $i"
	/sbin/modprobe $i
	status 
done

if [ ! -s /var/lib/detected-modules ]; then
	mount -t usbfs usbfs /proc/bus/usb
	/sbin/tazhw init
fi

# Try to release http link (from slitaz-loram-http package)
 release_http()
 {
	FREEMEM=$(free | awk '{ n = $NF } END { print n }')	
	if [ $FREEMEM -gt $(du -s $FS | awk '{ print $1+40000 }') ]; then
		status
		if ! grep -q " keep-loram" /proc/cmdline &&
		    [ -d $FS -o $FREEMEM -gt $(du -s $FS | \
			awk '{ print ($1*4)+40000 }') ]; then
			echo -n "Extracting loram..."
			. /etc/tazlito/loram.extract /cdrom
			if status; then
				umount /cdrom && umount /cdrom
				rmdir /cdrom
				yes y | tazpkg remove slitaz-loram-http > /dev/null
				return 0
			fi
		fi
		echo -n "Loading /usr in memory..."
		cp -a $FS /.usr.fs
		status
		echo -n "Releasing HTTP link..."
		umount /cdrom && umount /cdrom
		FS=/.usr.fs
		if [ -d $FS ]; then
			rm -f /$usr
			mv $FS /usr
		fi
	fi
	return 1
 }

# Mount /usr (from slitaz-loram-http package)
 while [ -d /cdrom ]; do
	/etc/init.d/network.sh
	RUN_SCRIPTS="$(echo $RUN_SCRIPTS | sed 's/network.sh//')"
	release=$(cat /etc/slitaz-release)
	iso1=iso/$release/flavors/slitaz-$release-loram-cdrom.iso
	iso2=iso/$release/flavors/slitaz-loram-cdrom.iso
	URLISO=http://mirror.switch.ch/ftp/mirror/slitaz/$iso1,\
http://mirror.switch.ch/ftp/mirror/slitaz/$iso2,\
http://mirror.slitaz.org/$iso1,\
http://mirror.slitaz.org/$iso2,\
http://download.tuxfamily.org/slitaz/$iso1,\
http://download.tuxfamily.org/slitaz/$iso2,\
http://mirror1.slitaz.org/$iso1,\
http://mirror1.slitaz.org/$iso2,\
http://mirror2.slitaz.org/$iso1,\
http://mirror2.slitaz.org/$iso2,\
http://mirror3.slitaz.org/$iso1,\
http://mirror3.slitaz.org/$iso2
	grep -q " urliso=" /proc/cmdline && URLISO=$(cat /proc/cmdline | sed 's/.* urliso=\([^ ]*\).*/\1/'),$URLISO
	for i in $(echo $URLISO | sed 's/,/ /g'); do
		/bin/httpfs $i /cdrom && rm -rf /usr/* && break
	done
	mount -o loop,ro /cdrom/*.iso /cdrom
	if [ -d /.usr.rw -a -x /bin/funionfs ]; then
		echo -n "Mounting /usr read-write... "
		usr=.usr.ro
	else
		echo -n "Mounting /usr read-only... "
		usr=usr
	fi
	FS=/cdrom/usr.cromfs
	if [ -x /bin/cromfs-driver -a -f $FS ]; then
		mkdir /$usr
		ln -s /usr/.moved /.moved
		release_http && break
		/bin/cromfs-driver $FS /$usr -o ro,dev,suid,allow_other
	elif grep -q squashfs /etc/filesystems && [ -f /cdrom/usr.sqfs ]; then
		FS=/cdrom/usr.sqfs
		ln -s /usr/.moved /.moved
		mkdir /$usr
		release_http && break
		mount -o loop,ro -t squashfs $FS /$usr
	elif grep -q squashfs /etc/filesystems && [ -f /cdrom/rootfs.gz ]; then
		FS=/cdrom/rootfs.gz
		ln -s /.rootfs /.moved
		mkdir /.rootfs
		release_http && break
		mount -o loop,ro -t squashfs $FS /.rootfs
		ln -s /.rootfs/usr /$usr
	elif [ -d /cdrom/usr ]; then
		FS=/cdrom/usr
		ln -s /usr/.moved /.moved
		rm -rf /$usr
		ln -s $FS /$usr
	else
		FS=/cdrom/fs/usr
		ln -s /cdrom/fs /.moved
		rm -rf /$usr
		ln -s $FS /$usr
	fi
	status 
	if [ -d /.usr.rw -a -x /bin/funionfs ]; then
		/bin/funionfs -o dirs=/.usr.ro=RO:/.usr.rw -o allow_other,nonempty -o suid,dev NONE /usr
	fi
	if [ -d /.moved/lib/modules ]; then
		rm -rf /lib/modules
		ln -s /.moved/lib/modules /lib/modules
	fi
	break
 done

# Handle kernel cmdline parameter config=<device>,<path> to source a 
# disk init script
if [ -n "$CONFIG" ]; then
	DEVICE=${CONFIG%,*}
	SCRIPT=${CONFIG#*,}
	echo "Probing $DEVICE... "
	if ! /bin/mount -r $DEVICE /mnt; then
		if echo $DEVICE | grep -Eq "/dev/sd|UUID=|LABEL="; then
			USBDELAY=`cat /sys/module/usb_storage/parameters/delay_use`
			USBDELAY=$((1+$USBDELAY))
			echo "$DEVICE is potentially a USB device: sleep for $USBDELAY seconds"
			sleep $USBDELAY
		fi
		if ! /bin/mount -r $DEVICE /mnt; then
			CONFIG=""
		fi
	fi
	echo -n "Source $SCRIPT from $DEVICE..."
	if [ -n "$CONFIG" ]; then
		. /mnt/$SCRIPT
		/bin/umount /mnt 2> /dev/null || true
	fi
	status 
fi

# Mount /proc/bus/usb.
if [ -d /proc/bus/usb ] && ! grep -q /proc/bus/usb /proc/mounts; then
	echo -n "Mounting /proc/bus/usb filesystem..."
	/bin/mount -t usbfs usbfs /proc/bus/usb
	status
fi

# Start syslogd and klogd.
if [ "$KERNEL_LOG_DAEMONS" = "yes" ]; then
	echo -n "Starting system log deamon: syslogd..."
	/sbin/syslogd -s $SYSLOGD_ROTATED_SIZE && status
	echo -n "Starting kernel log daemon: klogd..."
	/sbin/klogd && status
else
	echo "Kernel log daemons are disabled in /etc/rc.conf..."
fi

# Load all modules listed in config file.
if [ -n "$LOAD_MODULES" ]; then
	for mod in $LOAD_MODULES
	do
		modprobe $mod
	done
fi

# Be quiet on configuration to avoid messages overwriting ncurses dialog
echo "0 0 0 0" > /proc/sys/kernel/printk

# Detect PCI and USB devices with Tazhw from slitaz-tools. We load
# kernel modules only at first boot or in LiveCD mode.
if [ ! -s /var/lib/detected-modules ]; then
	/sbin/tazhw init
fi

# Call udevadm trigger to ensure /dev is fully populate now that all 
# modules are loaded.
if [ "$UDEV" = "yes" ]; then
	echo -n "Requesting events from the Kernel..."
	udevadm trigger
	status
fi

# Start all scripts specified with $RUN_SCRIPTS.
echo "Executing all initialization scripts..."
for script in $RUN_SCRIPTS
do
	if [ -x /etc/init.d/$script ]; then
		/etc/init.d/$script
	fi
done

# Re-source main config file. In Live mode, daemons list can be modified 
# by boot options (screen=text will remove slim).
. /etc/rcS.conf

# Start all daemons specified with $RUN_DAEMONS.
echo "Starting all daemons specified in /etc/rcS.conf..."
for daemon in $RUN_DAEMONS
do
	if [ -x /etc/init.d/$daemon ]; then
		/etc/init.d/$daemon start
	fi
done

# Back to a verbose mode.
echo "7 4 1 7" > /proc/sys/kernel/printk

# Reset screen and display a bold message.
if [ -n "$MESSAGE" ]; then
	/usr/bin/reset
	echo -e "\033[1m$MESSAGE\033[0m"
fi

# Display and log boot time.
time=$((`date +%s` - $bootdate))
echo $time > /var/log/boot-time
echo "SliTaz boot time: ${time}s"

fi # logged
