#!/bin/sh

# Options to kernel commandline
#
# fscache=[auto][,][init][,][/dev/*]
#
# nfsroot=ip:/dir
#
# aufs=[dir1][,][dir2]
#

export PATH=/bin:/sbin
umask 0077
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t tmpfs tmpfs /dev
mount -t tmpfs tmpfs /tmp

busybox --install -s
mdev -s
echo /bin/mdev > /proc/sys/kernel/hotplug
cp /proc/mounts /etc/mtab

for p in $(cat /proc/cmdline); do
	case "${p%=*}" in
		fscache)
			fscopt="${p##*=}"
			echo "fscopt=$fscopt"
		;;
		nfsroot)
			nfsroot="${p##*=}"
			echo "nfsroot=$nfsroot"
		;;
		aufs)
			aufsopt="${p##*=}"
			echo "aufsopt=$aufsopt"
		;;
	esac
done

if [ "$fscopt" != "" ]; then
	fscauto="no"
	fscinit="no"
	fscdev=""
	for o in $(echo "$fscopt" | tr -s ',' ' '); do
		case "$o" in
			auto)
				fscauto="yes"
			;;
			init)
				fscinit="yes"
			;;
			/dev/*)
				fscdev="$o"
				fscauto="no"
			;;
		esac
	done
	echo "fscauto=$fscauto fscinit=$fscinit fscdev=$fscdev"
fi

if [ "$nfsroot" != "" ]; then
	echo "nfsroot=$nfsroot"
fi

if [ "$aufsopt" != "" ]; then
	echo "Inserting aufs"
	insmod /modules/aufs.ko
fi

if [ "$fscopt" != "" ]; then
	if [ "$fscauto" == "yes" ]; then
		echo "Searching local cache"
		for d in $(ls /dev/hd?? /dev/sd?? 2>/dev/null) ; do
			echo "Looking at /dev/$d"
			if [ "$(e2label /dev/$d)" == "FSCache" ]; then
				fscdev = /dev/$d
				echo "Using $fscdev as cache"
				break
			fi
		done
	fi
	if [ "$fscinit" == "yes" ]; then
		echo "Initializing local cache device"
		mke2fs -j -m 0 $fscdev
		tune2fs -o user_xattr -L FSCache $fscdev
	fi
	echo "Mounted FSCache on $fscdev"
	mount $fscdev /fscache -o user_xattr
	echo "Starting cachefilesd"
	cachefilesd # -s
fi

if [ "$nfsroot" != "" ]; then
	echo "Mounting $nfsroot as /"
	if [ "$aufsopt" != "" ]; then
		echo "Setting to ro"
		nfsopt=",ro"
	fi
	if [ "$fscopt" != "" ]; then
		echo "Activating FSCache on /"
		nfsopt=$nfsopt",fsc"
	fi
	/bin/mount.nfs $nfsroot /newroot -o tcp,nolock,hard,intr,rsize=8192$nfsopt

	if [ "$fscopt" != "" ]; then
		echo "Bindmount FSCache"
		mount --bind /fscache /newroot/local/fscache
	fi

	for a in $(echo "$aufsopt" | tr -s ',' ' '); do
		echo "Mount aufs for $a"
		mount -t tmpfs aufs /newroot/mnt/unionfs/$a
 		mount -t aufs -o dirs=/newroot/mnt/unionfs/$a=rw:/newroot/$a=ro none /newroot/$a
	done

fi

echo > /proc/sys/kernel/hotplug
umount -l /proc /sys /dev /tmp
exec switch_root /newroot /sbin/init
