#!/bin/busybox sh
#
# By Chih-Wei Huang <cwhuang@linux.org.tw>
# Last updated 2009/07/18
#
# License: GNU Public License
# We explicitely grant the right to use the scripts
# with Android-x86 project.
#

try_mount()
{
	RW=$1; shift
	# FIXME: any way to mount ntfs gracefully?
	mount -o $RW $@ || mount.ntfs-3g -o rw,force $@
}

if [ -n "$DEBUG" ]; then
	LOG=/tmp/log
	set -x
else
	LOG=/dev/null
	[ -e $LOG ] || busybox mknod $LOG c 1 3
fi
exec 2> $LOG

busybox mount -t proc proc /proc
busybox mount -t sysfs sys /sys

busybox --install -s

export PATH=$PATH:/system/bin

if [ -n "$DEBUG" -o -n "$INSTALL" ]; then
	mknod /dev/tty2 c 4 2 && openvt
	mknod /dev/tty3 c 4 3 && openvt
else
	echo 0 0 0 0 > /proc/sys/kernel/printk
fi

echo -n Detecting Android...

while [ 1 ]; do
	mdev -s

	for device in /dev/sr* /dev/sd[a-z]*; do
		try_mount ro $device /mnt || continue
		cd /mnt/$SRC
		if [ ! -e ramdisk.img -o ! \( -e system.img -o -e system.sfs \) ]; then
			cd /
			umount /mnt
			continue
		fi
		mount -t tmpfs tmpfs /android
		cd /android
		zcat /mnt/$SRC/ramdisk.img | cpio -id > /dev/null
		if [ -e /mnt/$SRC/system.sfs ]; then
			mount -o loop /mnt/$SRC/system.sfs /sfs
			mount -o loop /sfs/system.img system
		else
			mount -o loop /mnt/$SRC/system.img system
		fi
		mkdir cache sdcard
		mount -t tmpfs tmpfs cache
		echo " found at $device"
		break
	done
	mountpoint -q /android && break
	sleep 1
	echo -n .
done

ln -s android/system /

ln -s ../system/lib/modules /lib

if [ -n "$INSTALL" ]; then
	cd /
	zcat /mnt/$SRC/install.img | cpio -iud > /dev/null
fi

if [ -n "$DEBUG" -o -n "$BUSYBOX" ]; then
	mv /bin /lib .
	system/bin/ln -s android/lib /lib
	system/bin/ln -s android/bin /bin
	sed -i 's|\(PATH *\)\(/sbin\)|\1/bin:\2|;s|\(/system\)\(/bin/sh\)|\2|' init.rc
	mv /sbin/* sbin
	rmdir /sbin
	ln -s android/sbin /
else
	ln -s ../android/sbin/hotplug /sbin
fi

if [ -n "$DEBUG" ]; then
	echo -e "\nType 'exit' to continue booting...\n"
	sh
fi

# load scripts
for s in `ls /scripts/* /mnt/$SRC/scripts/*`; do
	source $s
done

detect_hardware
do_install

load_modules
mount_data
mount_sdcard

if [ -n "$DEBUG" ]; then
	echo -e "\nUse Alt-F1/F2/F3 to switch between virtual consoles"
	echo -e "Type 'exit' to enter Android...\n"

	# FIXME: all error messages in the shell are sent to $LOG
	sh
	chroot /android /init
else
	exec switch_root /android /init
fi

sh # avoid kernel panic
