#!/bin/sh
# Copyright (C) 2006 OpenWrt.org

is_dirty() {
	grep Broadcom /proc/cpuinfo >&- || return 1
	OFFSET="$(($(hexdump -v /dev/mtdblock/1 -s 20 -n 2 -e '"%d"')-1))"
	return $(hexdump -v /dev/mtdblock/1 -s $OFFSET -n 1 -e '"%d"')
}

if [ "$1" != "failsafe" ]; then 

	boot_dev=$(nvram get boot_dev)
	boot_dev_mounted=0

	insmod ide-core
	#hardware specific IDE module
	case "$(cat /proc/diag/model)" in
		"ASUS WL-700gE") insmod aec62xx;;
		"ASUS WL-HDD") insmod pdc202xx_old;;
	esac
	insmod ide-detect
	insmod ide-disk
	insmod jbd
	insmod ext3

	mount -t ext3 -o rw "$boot_dev" /mnt 2>&-

	#if everything on HDD looks ok, do the pivot root to HDD
	if [ -d /mnt/sbin ] && [ -x /mnt/sbin/hotplug.failsafe ] && [ -d /mnt/rom ]; then

		#our old root will stay as /mnt/rom on the HDD
		echo "switching to $boot_dev"
        	pivot_root /mnt /mnt/rom        
        
        	# mount new dev, proc, sys
		mount -o move /rom/proc /proc
		mount -o move /rom/dev /dev
		mount -o move /rom/tmp /tmp

		boot_dev_mounted=1

	#if something is wrong, clean up and mount jffs2
	else
		echo "$boot_dev not ready yet; using jffs2"

		umount /mnt

		rmmod ext3
		rmmod jbd
		rmmod ide-disk
		rmmod ide-detect
		# hardware specific IDE module
		case "$(cat /proc/diag/model)" in
			"ASUS WL-700gE") rmmod aec62xx;;
			"ASUS WL-HDD") rmmod pdc202xx_old;;
		esac
		rmmod ide-core
	fi

	#if boot_dev failed, mount jffs2
	if [ $boot_dev_mounted = 0 ]; then

		mtd unlock linux
		mount | grep jffs2 >&-
		if [ $? = 0 ] ; then
			mount -o remount,rw /dev/root /
		else
			. /bin/firstboot
			is_dirty 
			[ $? != 0 ] && {
				echo "switching to jffs2"
				mount /dev/mtdblock/4 /jffs -t jffs2
				fopivot /jffs /rom
			} || {
				echo "jffs2 not ready yet; using ramdisk"
				ramoverlay
			}
		fi
	fi
fi

mkdir -p /dev/pts
mount none /dev/pts -t devpts 2>&-
grep sysfs /proc/filesystems >/dev/null && mount -t sysfs none /sys 2>&-
