#!/bin/busybox sh

echo "Welcome to our world!"

#Mount things needed by this script
mount -t proc proc /proc
mount -t sysfs sysfs /sys

#Disable kernel messages from popping onto the screen
# echo 0 > /proc/sys/kernel/printk

#Clear the screen
# clear

#Create all the symlinks to /bin/busybox
# busybox --install -s

#Create device nodes
#mdev -s

#Function for parsing command line options with "=" in them
# get_opt("init=/sbin/init") will return "/sbin/init"
get_opt() {
	echo "$@" | cut -d "=" -f 2
}

#Defaults
init="/sbin/init"
root="/dev/mmcblk0p4"
root_offset="1024"
image="/kindle~1.img"
console="/dev/ttymxc0"

#Process command line options
for i in $(cat /proc/cmdline); do
	case $i in
#		root\=*)
#			root=$(get_opt $i)
#			;;
		rootoffset\=*)
			root_offset=$(get_opt $i)
			;;
		init\=*)
			init=$(get_opt $i)
			;;
		image\=*)
			image=$(get_opt $i)
			;;
	esac
done

#Mount the root device
losetup /dev/loop0 "${root}" -o "${root_offset}"
mount /dev/loop0 /mnt/rootdev

# Mount the root image
mount -o loop "/mnt/rootdev${image}" /mnt/newroot

# extract modules
tar -xz -C /mnt/newroot < linux-2.6.22.19-lab126.tar.gz

#Check if $init exists and is executable
if [[ -x "/mnt/newroot/${init}" ]] ; then
	#Unmount all other mounts so that the ram used by
	#the initramfs can be cleared after switch_root
	umount /sys /proc
	
	#Switch to the new root and execute init
	exec switch_root -c "${console}" /mnt/newroot "${init}"
fi

#This will only be run if the exec above failed
echo "Failed to switch_root, dropping to a shell"
exec sh
