#!/bin/sh

mount -t proc proc /proc
ROOT=
NFSROOT=
export init=/sbin/init
for x in $(cat /proc/cmdline); do
	case $x in
		init=*)
			init=${x#init=}
			;;
		root=*)
			ROOT=${x#root=}
			;;
		nfsroot=*)
			NFSROOT=${x#nfsroot=}
			;;
	esac
done

mount -t sysfs sysfs /sys

mount -t devtmpfs -o nosuid,mode=0755 devtmpfs /dev

mkdir -p /dev/pts
mkdir -p /dev/shm
mount -t devpts devpts /dev/pts
mount -t tmpfs tmpfs /dev/shm
mount -t tmpfs tmpfs /tmp
mount -t tmpfs tmpfs /run

if [ "x${ROOT}" = "x" ]; then
	exec /sbin/init
fi

export ROOT

mkdir /rootfs
if [ $ROOT == "/dev/nfs" ] && [ "x${NFSROOT}" != "x" ];then
	/sbin/ifup -a
	mount -t nfs -o nolock $NFSROOT /rootfs
else
	cnt=0
	while [ $cnt -lt 100 ]
	do
		if [ ! -e $ROOT ];then
			sleep 0.1
		else
			echo "find $ROOT: $cnt"
			break
		fi
		let cnt++
	done
	mount $ROOT /rootfs/
	if [ ! -e /rootfs/dev/console ]; then
		/bin/mknod /rootfs/dev/console c 5 1
	fi
	if [ ! -e /rootfs/dev/null ]; then
		/bin/mknod /rootfs/dev/null c 1 3
	fi
fi

mount -n -o move /proc /rootfs/proc
mount -n -o move /sys /rootfs/sys
mount -n -o move /run /rootfs/run
mount -n -o move /tmp /rootfs/tmp
mount -n -o move /dev /rootfs/dev
mount -n -o move /dev/shm /rootfs/dev/shm
mount -n -o move /dev/pts /rootfs/dev/pts

exec run-init /rootfs "${init}" "$@" <"/rootfs/dev/console" >"/rootfs/dev/console" 2>&1
echo "Something went badly wrong in the initramfs."
