#!/bin/sh
export PATH=/bin:/sbin:/usr/bin:/usr/sbin

mount none /proc -t proc
insmod ff-diag && echo 0x01 > /proc/sys/diag

insmod switch-core
insmod switch-robo || insmod switch-adm || rmmod switch-core

ff_nonetmsg=$(nvram get ff_nonetmsg)
[ -d /proc/switch/eth0 ] && [ "1" != "$ff_nonetmsg" ] && {
	v0p="$(cat /proc/switch/eth0/vlan/0/ports)"
	v1p="$(cat /proc/switch/eth0/vlan/1/ports)"
	v2p="$(cat /proc/switch/eth0/vlan/2/ports)"
	echo 1 > /proc/switch/eth0/reset

	# 0x0467 is wrt54gl
	case "$(nvram get boardtype)" in
		0x0467|0x042f) echo "0 1 2 3 5u*";;
		            *) echo "1 2 3 4 5u*";;
	esac > /proc/switch/eth0/vlan/0/ports
}

ip link set dev eth0 up
ip addr add dev eth0 192.168.1.1/24 broadcast 192.168.1.255
netmsg 192.168.1.0 "(dummy message)" # b44 eats the first packet
netmsg 192.168.1.255 "Press reset now, to enter Failsafe!"
sleep 1

mount none /tmp -t ramfs
ff_reset=$(nvram get ff_reset)
checksum=$(dd if=/dev/mtd/1ro bs=32 count=1 2>/dev/null|md5sum|cut -d' ' -f1)
if [ "$checksum" != "$ff_reset" ] || [ "on" != "$(nvram get boot_wait)" ]; then
	echo 0x00 > /proc/sys/diag
	nvram set boot_wait=on
	nvram set ff_reset=$checksum
	nvram commit
	echo 0x01 > /proc/sys/diag
fi
test $(cat /proc/sys/reset) = 1 && ff_reset=failsafe

if [ "$checksum" = "$ff_reset" ]; then
	mtd unlock mtd4
	mount -t jffs2 /dev/mtdblock/4 /jffs || unset ff_reset
elif [ "readonly" = "$ff_reset" ]; then
	mount -o ro -t jffs2 /dev/mtdblock/4 /jffs && export READONLY=true || unset ff_reset
fi

if [ "$checksum" = "$ff_reset" ] || [ "readonly" = "$ff_reset" ]; then
	ip addr flush dev eth0
	[ -d /proc/switch/eth0 ] && [ "1" != "$ff_nonetmsg" ] && {
		echo "$v0p" > /proc/switch/eth0/vlan/0/ports
		echo "$v1p" > /proc/switch/eth0/vlan/1/ports
		echo "$v2p" > /proc/switch/eth0/vlan/2/ports
	}
	root=/jffs
	if [ "0" != "$(nvram get ff_mini_fo)" ]; then
		if [ "readonly" = "$ff_reset" ]; then
			mount -t mini_fo -o base=/,sto=/jffs,ro none /mnt
		else
			mount -t mini_fo -o base=/,sto=/jffs none /mnt
			if [ -L /mnt/bin/rmdir ]; then
				rm -f /mnt/bin/rmdir
				cat>/mnt/bin/rmdir<<EOF
#!/bin/sh
r=0
for d in \$*;do
	if [ -n "\$(ls -a \$d|sed -e '/^\.\.\?\$/d')" ];then
		echo "\$d: Directory not empty">&2
		r=1
	else
		busybox rmdir \$d||r=1
	fi
done
exit \$r
EOF
				chmod +x /mnt/bin/rmdir
			fi
		fi
		root=/mnt
	fi
	pivot_root $root $root/rom
	mount none /proc -t proc
	mount -o move /rom/dev /dev
	mount -o move /rom/tmp /tmp
	umount rom/proc
elif [ "failsafe" = "$ff_reset" ]; then
	while :; do { echo $(((X=(X+1)%8)%2)) > /proc/sys/diag; sleep $((X==0)); } done &
	export FAILSAFE=true
	netmsg 192.168.1.255 "Entering Failsafe!"
else
	firstboot
	echo 0x04 > /proc/sys/diag
	export REBOOT=true
	netmsg 192.168.1.255 "Reboot scheduled!"
fi
exec /sbin/init
