#!/bin/sh
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
mount none /proc -t proc
insmod diag
echo 0x01 > /proc/sys/diag

ip link set dev eth0 up
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
	echo "0 1 2 3 4 5u*" > /proc/switch/eth0/vlan/0/ports
}

# this delay is apparently necessary because the link isn't up yet
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
  netmsg 192.168.1.255 "Entering Readonly!"
  export READONLY=true
  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
  netmsg 192.168.1.255 "Entering Failsafe!"
  export FAILSAFE=true
  while :; do { echo $(((X=(X+1)%8)%2)) > /proc/sys/diag; sleep $((X==0)); } done &
else
  netmsg 192.168.1.255 "Normal startup."
  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 -f rom/proc rom/dev
fi
mount none /tmp -t ramfs
# 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
}
ip addr flush dev eth0
exec /sbin/init
