#!/bin/sh

IBPATH=${IBPATH:-@IBSCRIPTPATH@}

function usage() {
	echo Usage: `basename $0` "[-h] [-N | -nocolor] [<topology-file>" \
	    "| -C ca_name -P ca_port -t(imeout) timeout_ms]"
	exit -1
}

function user_abort() {
	echo "Aborted"
	exit 1
}

trap user_abort SIGINT

gflags=""
verbose=""
v=0
oldlid=""
topofile=""
ca_info=""

while [ "$1" ]; do
	case $1 in
	-h)
		usage
		;;
	-N|-nocolor)
		gflags=-N
		;;
	-P | -C | -t | -timeout)
		case $2 in
		-*)
			usage
			;;
		esac
		if [ x$2 = x ] ; then
			usage
		fi
		ca_info="$ca_info $1 $2"
		shift
		;;
	-*)
		usage
		;;
	*)
		if [ "$topofile" ]; then
			usage
		fi
		topofile="$1"
		;;
	esac
	shift
done

if [ "$topofile" ]; then
	netcmd="cat $topofile"
else
	netcmd="$IBPATH/ibnetdiscover $ca_info"
fi

text="`eval $netcmd`"
rv=$?
echo "$text" | awk '

function clear_all_errors(lid, port)
{
	if (system("'$IBPATH'/perfquery'"$ca_info"' '$gflags' -R -a " lid " " port " 0x0fff"))
		nodeerr++
}

function clear_errors(lid, port)
{
	if (system("'$IBPATH'/perfquery'"$ca_info"' '$gflags' -R " lid " " port " 0x0fff"))
		nodeerr++
}

/^Ca/ || /^Switch/ || /^Rt/ {
			nnodes++
			ntype=$1; nodeguid=substr($3, 4, 16); ports=$2
			if (ntype != "Switch")
				next

			lid = substr($0, index($0, "port 0 lid ") + 11)
			lid = substr(lid, 1, index(lid, " ") - 1)
			clear_all_errors(lid, 255)
		}

/^\[/   {
			port = $1
			sub("\\(.*\\)", "", port)
			gsub("[\\[\\]]", "", port)
			if (ntype != "Switch") {
				lid = substr($0, index($0, " lid ") + 5)
				lid = substr(lid, 1, index(lid, " ") - 1)
				clear_errors(lid, port)
			}
		}

/^ib/	{print $0; next}
/ibpanic:/	{print $0}
/ibwarn:/	{print $0}
/iberror:/	{print $0}

END {
	printf "\n## Summary: %d nodes cleared %d errors\n", nnodes, nodeerr
}
'
exit $rv
