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

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

ifname=eth0
# WAP54G, WL-HDD
[  "$(nvram get boardnum)" = "2" \
-o \( "$(nvram get boardnum)" = "asusX" \
   -a "$(nvram get et1phyaddr)" -eq 1 \) ] && ifname="eth1"

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

	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
}

ifconfig $ifname 192.168.1.1 netmask 255.255.255.0 broadcast 192.168.1.255 up
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

if [ $(cat /proc/sys/reset) = 1 -o "$(nvram get failsafe)" = 1 ]; then
	while :; do { echo $(((X=(X+1)%8)%2)) > /proc/sys/diag; sleep $((X==0)); } done &
	export FAILSAFE=true
	[ "$(nvram get boot_wait)" != "on" ] && {
		nvram set boot_wait=on
		nvram commit
	}
	netmsg 192.168.1.255 "Entering Failsafe!"
	telnetd -l /bin/login <> /dev/null 2>&1
else
	ifconfig $ifname 0.0.0.0

	# revert to the boot loader's vlan config
	# required for at least WRT54G v1.1
	[ -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
	}
fi

mount_root ${FAILSAFE:+failsafe}

exec /sbin/init
