#!/bin/sh

CONFIG=/bin/config
WIFI_DONE_FILE="/tmp/wifi_is_done"

stop()
{
	[ "$($CONFIG get factory_mode)" = "1" ] && return
	ethctl eth1 phy-power down
	ethctl eth2 phy-power down
	ethctl eth3 phy-power down
	ethctl eth4 phy-power down
}

start()
{
	[ "$($CONFIG get factory_mode)" = "1" ] && return
	ethctl eth1 phy-power up
	ethctl eth2 phy-power up
	ethctl eth3 phy-power up
	ethctl eth4 phy-power up
}

restart()
{
	stop
	if [ "x$1" = "x6" ]; then
		sleep 3
	else
		sleep 8
	fi
	start
}

factory_handle()
{
	local status="$1"

	[ "$($CONFIG get factory_mode)" != "1" ] && return
	ethctl eth0 phy-power $status
	ethctl eth1 phy-power $status
	ethctl eth2 phy-power $status
	ethctl eth3 phy-power $status
	ethctl eth4 phy-power $status
}

factory_start()
{
        local wait_time="60"

	[ "$($CONFIG get factory_mode)" != "1" ] && return
        while [ "$wait_time" -gt "0" ]; do
		wait_time=$(( $wait_time - 1 ))
                sleep 2
		[ -f $WIFI_DONE_FILE ] && break
        done

	factory_handle up
	/sbin/ledcontrol -n power -c amber -s on
}

case "$1" in
	start)
	start
	;;
	stop)
	stop
	;;
	restart)
	restart $2
	;;
	factory_stop)
	factory_handle down
	;;
	factory_start)
	factory_start &
	;;
esac
