#!/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.
#

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" ]; then
	mknod /dev/tty2 c 4 2 && openvt
	mknod /dev/tty3 c 4 3 && openvt
fi

echo -n Detecting Android...

while [ 1 ]; do
	mdev -s

	for device in /dev/sr* /dev/sd[a-z]*; do
		mount -o ro $device /mnt || continue
		cd /mnt/$SRC
		if [ ! -e ramdisk.img -o ! \( -e system.img -o -e system.sfs \) ]; then
			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 "$DEBUG" -o -n "$BUSYBOX" ]; then
	mv /bin /lib /android
	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/* /android/sbin
	rmdir /sbin
	ln -s android/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

load_modules

[ -n "$INSTALL" ] && install_hd

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 # aviod kernel panic
