#!/bin/sh

. /lib/switch/switch_functions

# get port state
# $1: portid
get_port_state()
{
	local port_state=0
	local port_speed=0
	local port_dup_mode=0
	local port_flowcontrol="off"
	
	local port=`get_port_index $i`
	if [ "$port" = "none" ]; then
		return
	fi
	local state=`swconfig dev switch0 port $port get link | grep up`
	if [ "x$state" != "x" ]; then
		port_state="connected"
		local speed=`echo $state | awk -F ':' '{print $4}' |tr -cd "[0-9]"`
		if [ $speed == "1000" ]; then
			port_speed="1000M"
		elif [ $speed == "100" ]; then
			port_speed="100M"
		elif [ $speed == "10" ]; then
			port_speed="10M"
		elif [ $speed == "2500" ]; then
			port_speed="2500M"
		else
			port_speed="10000M"
		fi

		dup_mode=`echo $state | grep full`
		if [ "x$dup_mode" != "x" ]; then
			port_dup_mode="Full"
		else
			port_dup_mode="Half"
		fi
			
		flowcontrol=`echo $state | grep flow`
		if [ "x$flowcontrol" != "x" ]; then
			port_flowcontrol="on"
		else
			port_flowcontrol="off"
		fi			
	else
		port_state="disconnected"
		port_speed="---"
		port_dup_mode="---"
		port_flowcontrol="---"
	fi

	echo "Port $port:"
	echo "   state       : $port_state "
	echo "   speed       : $port_speed "
	echo "   dup_mode    : $port_dup_mode "
	echo "   flowcontrol : $port_flowcontrol "
	echo ""
}


stata_arg_check()
{
	local portsid=$1

	for i in $portsid; do
		if [ `expr match $i "[0-9]"` = 0 ] ;then
		echo "[state] port is invalid. "
		exit 0
		fi
	done
}
# cn9130 switch get port state
# $1: op (get)
# $2: portsid (1.2.3.4.5...)
cn9130_switch_port_state()
{
	local op=$1
	local portsid=$2

	if [ $op = "get" ]; then	
		stata_arg_check "$portsid"
		if [ -z "$portsid" ]; then
			portsid=`uci get switch.global.switch0_port_list`
		fi
		for i in $portsid; do			
			get_port_state $i
		done
	else
		echo "[state] error op. (get)"
	fi
}