#!/bin/sh

IBPATH=${IBPATH:-@IBSCRIPTPATH@}

usage() {
	echo Usage: `basename $0` "[-h] [-v] [-N | -nocolor] [-G]" \
	    "[-C ca_name] [-P ca_port] [-t(imeout) timeout_ms] <lid|guid>"
	exit 255
}

green() {
	if [ "$bw" = "yes" ]; then
		if [ "$verbose" = "yes" ]; then
			echo $1
		fi
		return
	fi
	if [ "$verbose" = "yes" ]; then
		echo -e "\\033[1;032m" $1 "\\033[0;39m"
	fi
}

red() {
	if [ "$bw" = "yes" ]; then
		echo $1
		return
	fi
	echo -e "\\033[1;031m" $1 "\\033[0;39m"
}

guid_addr=""
bw=""
verbose=""
ca_info=""
suppress_deprecated="no"

while [ "$1" ]; do
	case $1 in
	-G)
		guid_addr=yes
		;;
	-nocolor|-N)
		bw=yes
		;;
	-v)
		verbose=yes
		;;
	-P | -C | -t | -timeout)
		case $2 in
		-*)
			usage
			;;
		esac
		if [ x$2 = x ] ; then
			usage
		fi
		ca_info="$ca_info $1 $2"
		shift
		;;
	-S)
		suppress_deprecated="yes"
		;;
	-*)
		usage
		;;
	*)
		break
		;;
	esac
	shift
done

if [ -z "$1" ]; then
	usage
fi

if [ "$suppress_deprecated" = "no" ]; then
/usr/bin/echo -e "*** WARNING ***: this command is deprecated; Please use \"smpquery nodeinfo\"\n\n" 1>&2
fi

if [ "$guid_addr" ]; then
	if ! lid=`$IBPATH/ibaddr $ca_info -G -L $1 | awk '/failed/{exit 255} {print $3}'`; then
		echo -n "guid $1 address resolution: "
		red "FAILED"
		exit 255
	fi
else
	lid=$1
	if ! temp=`$IBPATH/ibaddr $ca_info -L $1 | awk '/failed/{exit 255} {print $1}'`; then
		echo -n "lid $1 address resolution: "
		red "FAILED"
		exit 255
	fi
fi

## For now, check node only checks if node info is replied

if $IBPATH/smpquery $ca_info nodeinfo $lid > /dev/null 2>&1 ; then
	if [ "$verbose" = "yes" ]; then
		echo -n "Node check lid $lid: "
		green OK
	fi
	exit 0
else
	echo -n "Node check lid $lid: "
	red FAILED
	exit 255
fi
