#!/bin/sh
#
#

gpio_config() {
	local kernel_version=$(uname -r | awk -F '-' -e '{print $1}' | sed -e 's/\.//g')
	local gpio_offset=
	local gpio_num=
	local GPIO=

	NUM=$1
	DIR=$2

	# check which kernel version we are running on to use the proper gpio offset
	if [ $kernel_version -eq 390 ]; then
		gpio_offset=0
	else
		gpio_offset=906
	fi

	gpio_num=$(($gpio_offset + $NUM))
	GPIO=/sys/class/gpio
	echo $gpio_num > $GPIO/export
	echo $DIR > $GPIO/gpio$gpio_num/direction
	if test "$DIR" = in ; then
		cat $GPIO/gpio$gpio_num/value
	else
		echo $3 > $GPIO/gpio$gpio_num/value
	fi
	echo $gpio_num > $GPIO/unexport
}

reset_switches() {
	# GPIO 48 = Switch 0
	# GPIO 49 = Switch 1
	gpio_config 48 out 0
	gpio_config 49 out 0
	usleep 2000
	gpio_config 48 out 1
	gpio_config 49 out 1
	usleep 2000
}

error() {
	echo "$1"
	exit
}

start() {
	echo "Starting switch, eth0 and eth1..."

	reset_switches
	source /tmp/eeprom
	ip link set lo up

	# Set the MAC addresses.
	ip link set eth0 addr $MAC0 up
	ip link set eth1 addr $MAC1 up

	# Bring up the switches, start daemon for link monitoring
	/ross/bin/mv88e63 init
	/ross/bin/mv88e63 daemon

	echo "OK"
}
stop() {
	echo -n "Stopping switch, eth0 and eth1..."
	pid=`pidof mv88e63`
	test "$pid" && kill $pid
	usleep 200
	ip link set eth1 down
	ip link set eth0 down
	ip link set lo down
	echo "OK"
}
restart() {
	stop
	start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload)
	restart
	;;
  *)
	echo $"Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?
