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

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

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

# save the boot loader's vlan config
# we need it on some routers that have no vlan*ports set
[ -d /proc/switch/eth0 ] && {
	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) 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 2

ff_reset=$(/usr/sbin/nvram get ff_reset)
if [ "$ff_reset" != "normal" ] || [ "$(/usr/sbin/nvram get boot_wait)" != "on" ]; then
	echo 0x00 > /proc/sys/diag
	/usr/sbin/nvram set boot_wait=on
	/usr/sbin/nvram set ff_reset=normal
	/usr/sbin/nvram commit
	echo 0x01 > /proc/sys/diag
fi
if [ -z "$ff_reset" ] || [ "$ff_reset" = "format" ]; then
	netmsg 192.168.1.255 "Reboot scheduled!"
	mount none /tmp -t ramfs
	/bin/firstboot
	echo 0x04 > /proc/sys/diag
	export REBOOT=true
elif [ "$ff_reset" = "readonly" ]; then
	export READONLY=true
	ip addr flush dev eth0
	[ -d /proc/switch/eth0 ] && {
		echo "$v0p" > /proc/switch/eth0/vlan/0/ports
		echo "$v1p" > /proc/switch/eth0/vlan/1/ports
		echo "$v2p" > /proc/switch/eth0/vlan/2/ports
	}
	mount -o ro -t jffs2 /dev/mtdblock/4 /jffs
	pivot_root /jffs /jffs/rom
	mount none /dev -t devfs
	mount none /proc -t proc
	umount -f rom/proc rom/dev
elif [ "$ff_reset" = "failsafe" ] || [ $(cat /proc/sys/reset) = 1 ]; 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
	ip addr flush dev eth0
	[ -d /proc/switch/eth0 ] && {
		echo "$v0p" > /proc/switch/eth0/vlan/0/ports
		echo "$v1p" > /proc/switch/eth0/vlan/1/ports
		echo "$v2p" > /proc/switch/eth0/vlan/2/ports
	}
	mtd unlock mtd4
	mount -t jffs2 /dev/mtdblock/4 /jffs
	pivot_root /jffs /jffs/rom
	mount none /dev -t devfs
	mount none /proc -t proc
	umount rom/proc
fi
mount none /tmp -t ramfs
exec /sbin/init
