#!/bin/sh
# linuxrc
# Copyright 2006 Mobilygen Corp.
# This script is called by the kernel when booting from an initial RAM disk.
VERSION=0.1;

ROOTFS_MOUNTPOINT="/rootfs";

echo "RAM disk linuxrc version ${VERSION}."

# Mount /proc, needed by modprobe
if [ ! -d /proc ]; then
	/bin/mkdir -p /proc;
	# If it fails, mount will fail
fi
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

if [ ! -d /rootfs/initrd ]; then
	/bin/mount /rootfs -o remount,rw
	if [ "X$?" != "X0" ]; then
		echo "ERROR: failed to remount rootfs read-write.";
	fi
	/bin/mkdir -p /rootfs/initrd
	if [ "X$?" != "X0" ]; then
		echo "ERROR: failed to create new mountpoint for initrd.";
	fi
	/bin/mount /rootfs -o remount,ro
	if [ "X$?" != "X0" ]; then
		echo "ERROR: failed to remount rootfs read-only.";
	fi
fi

# /proc is not needed anymore
/bin/umount /proc
if [ "X$?" != "X0" ]; then
	echo "WARNING: failed to un-mount temporary /proc.";
fi

/sbin/pivot_root /rootfs /rootfs/initrd;
if [ "X$?" != "X0" ]; then
	echo "ERROR: failed to re-mount / with the real 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

# Note: /initrd is still mounted, the init process will have to un-mount it
echo "Root filesystem is now mounted, start init."
exec /sbin/init
