#!/bin/sh
# linuxrc
# Copyright 2006 Mobilygen Corp.
# This script is called by the kernel when booting from an initial RAM disk.
VERSION=1.0;
export INITSCRIPTS_DIR="/etc/initramfs.d";
export CONF_DIR="/etc/sysconfig";
export HELPERS_DIR="${CONF_DIR}/helpers";
# This is needed for /rootfs /sbin/init to work properly
export CONSOLE=/dev/console

echo "initramfs script version ${VERSION}."

if [ ! -d ${INITSCRIPTS_DIR} ]; then
	# If there is not /etc/initramfs.d we do the old init
	ROOTFS_MOUNTPOINT="/rootfs";
	FSTYPE="$(/bin/grep /rootfs /etc/fstab | sed -e 's/[ ]*[^ ]\+[ ]\+[^ ]\+[ ]\+\([^ ]*\).*/\1/')";
	# Mount /proc, needed by modprobe
	if [ ! -d /proc ]; then
		/bin/mkdir -p /proc;
		# If it fails, mount will fail
	fi
	/bin/mount /proc /proc -t proc;
	if [ "X$?" != "X0" ]; then
		echo "WARNING: failed to mount /proc, the system may not work properly because of it.";
	fi
	while read MODULE ARGS; do
		MODULE=$(/bin/echo ${MODULE} | sed -e 's/#.*//');
		if [ ! "${MODULE}" ]; then
			continue;
		fi
		ARGS=$(/bin/echo ${ARGS} | sed -e 's/#.*//');
		/sbin/modprobe ${MODULE} ${ARGS};
		if [ "X$?" != "X0" ]; then
			echo "ERROR: failed to load module ${MODULE}.";
		fi
	done < /etc/modules;
	if [ ! -d ${ROOTFS_MOUNTPOINT} ]; then
		/bin/mkdir -p ${ROOTFS_MOUNTPOINT};
		if [ "X$?" != "X0" ]; then
			echo "ERROR: failed to create rootfs mountpoint.";
		fi
	fi
	/bin/mount /rootfs -o ro;
	if [ "X$?" != "X0" ]; then
		echo "ERROR: failed to mount root file-system.";
		echo "ERROR: THIS IS A FATAL ERROR.";
		if [ -x /bin/sh ]; then
			echo "Starting a shell to debug problem.";
			/bin/sh;
		else
			echo "System is going down ... ";
			exit 1;
		fi
	fi
	# /proc is not needed anymore
	/bin/umount /proc
	if [ "X$?" != "X0" ]; then
		echo "WARNING: failed to un-mount temporary /proc.";
	fi
else
	# New mode: we run all scripts in /etc/initramfs.d
	for script in $(ls ${INITSCRIPTS_DIR}/[0-9][0-9]*); do
		${script};
		if [ $? -ne 0 ]; then
			echo "ERROR: ${script} returned an error.";
			if [ -x /bin/sh ]; then
				echo "Starting a shell to debug problem.";
				/bin/sh;
			else
				echo "System is going down ... ";
				exit 1;
			fi
		fi
	done		
fi

echo "Root filesystem is now ready, start init."
exec /sbin/switch_root /rootfs /sbin/init;

# We should never reach this point (switch_root does not return)
echo "ERROR: switch_root returned which is not normal.";
echo "ERROR: THIS IS A FATAL ERROR.";
if [ -x /bin/sh ]; then
	echo "Starting a shell to debug problem.";
	/bin/sh;
else
	echo "System is going down ... ";
	exit 1;
fi
