#!/bin/bash

# Setup etherswitch

SW=/proc/driver/switch_api

# Determine hardware type
grep -q sata_sil /proc/bus/pci/devices
if [ $? -eq 0 ]; then
	CFG=/tmp/vlan.cfg
else
	CFG=/tmp/os_env
fi

[ -f $SW ] || insmod eswch

if [ "$1" = "start" ]; then

	. $CFG || exit
	[ "$os_vlan_enable" = "y" ] || exit
	[ "$os_vlan_split" ] && echo SwPortEnb 0 0 > $SW
	echo SwEnableVlan 1 > $SW
	for p in 0 1 2 3 4 5; do
		v="os_vlan_pvid"$p
		[ "${!v}" ] &&  echo SwVlanSetPvid $p "${!v}" > $SW
	done

	for f in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
		v="os_vlan_vid"$f
		m="os_vlan_mem"$f
		if [ "${!v}" -a "${!m}" ]; then
			mem="${!m}"
			[ ${#mem} -ne 6 ] && continue

			i=0
			j=1
			tagged=0
			members=0
			while [ $i -lt 6 ]; do
				case ${mem:$i:1} in
					"_" ) ;;
					"U" ) members=`expr $members + $j`;;
					"T" ) members=`expr $members + $j`; tagged=`expr $tagged + $j`;;
					* ) echo bad character in os_vlan_mem$f $mem; exit;;
				esac
				j=`expr $j \* 2`
				i=`expr $i + 1`
			done
			echo SwVlanSetFilter $f ${!v} $members $tagged > $SW
		fi
	done

	# It is possible to segment the switch and assign multiple interfaces and therefore multiple subnets
	# to groups of ports.
	# For example:
	#
	# eth0: 	LAN1-4
	# eth0.x:	LINK
	#
	# then ports LAN1-4 act as a 4-port switch, while the LINK port could connect to the internet (in the
	# same way that the back port of a 4100 can).

	if [ "$os_vlan_split" ]; then
		# enable LINK port
		echo SwPortEnb 0 1 > $SW

		# Create a new interface for the LINK network
		insmod 8021q && vconfig add eth0 $os_vlan_pvid0 && if2=eth0.$os_vlan_pvid0

		# The new interface will need an IP address.
		if [ "$os_vlan_split" = "D" ]; then
			dhcpcd -dYNR $if2
		else
			ifconfig $if2 $os_vlan_split
		fi

		# setup nat
		iptables -A POSTROUTING -t nat -o $if2 -j MASQUERADE
	fi

elif [ "$1" = "stop" ]; then

	echo SwEnableVlan 0 > $SW

else
	dmesg -c > /dev/null
	echo SwShowVlan > $SW
	dmesg -c 
fi

