#!/bin/ash
#
# Broadcom 47xx vlan and switch configuration init script
#
# Config: uses the 'nvram' settings for setting up vlan devices

. /etc/rc.d/init.d/functions

if [ ! -x /sbin/robocfg ]; then
	echo -n "Setting up vlan: /sbin/robocfg not found "
	false
	check_status
fi

if [ ! -x /sbin/vconfig ]; then
	echo -n "Setting up vlan: /sbin/vconfig not found "
	false
	check_status
fi

if [ ! -x /sbin/nvram ]; then
	echo -n "Setting up vlan: /sbin/nvram not found "
	false
	check_status
fi

case "$1" in
start)

	# Add a specific workaround for the case of weirdly set wireless mac address
	# Do what openwrt is doing, and increment the last hex with 2
	if [ "`nvram get il0macaddr`" = 00:90:4c:5f:00:2a ]; then
		et0="$(nvram get et0macaddr)"
		prefix="$(echo $et0 | sed -e 's/:..$//')"
		addendum=$(( (0x$(echo $et0 | sed -e s/.*://g) + 2) % 256 ))
		il0=$(printf %s:%02x $prefix $addendum)
		echo -n "Fixing up wlan0 mac address: "
		nvram set il0macaddr=$il0 && nvram commit
		check_status
		ifconfig wlan0 hw ether $il0 2>/dev/null
	fi

	# eth0 has to be up for this
	ifconfig eth0 up

	robocfg switch disable
	robocfg vlans enable reset

	nvram show | grep vlan[0-4]ports= | sed -e s/vlan// -e s/ports=/\ / |
	  while read vlan ports; do
		echo -n "Bringing up eth0.${vlan}: "
		robocfg vlan ${vlan} ports "${ports}" &&
		vconfig add eth0 $vlan
		check_status
	done
	robocfg switch enable
	exit 0
	;;
stop)
	# FIXME: Should we really do something at shutdown?
	exit 0
	;;
restart)
	$0 stop
	$0 start
	;;
status)
	robocfg show
	;;
*)
	echo "Usage: $0 {start|stop|restart|status}"
	exit 1
esac

