#!/bin/sh
#
# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@
#
#  version 0.01   Date: 2012-01-23
#  version 1.00   Date: 2012-09-20
#	added quick ping to verify if node is alive
#       added use "node info" if monitor is up.
#  This script is to ssh to physical node name via the logical node id
#  USAGE "sqssh <nid>" to ssh to the physical node

if [ $# -eq 1 ]
then
    if [ "$1" -eq "$1" ] 2>/dev/null; then

	VARLEN=`expr length $1`
	if [ `expr length $1` -le "3" ]
	    then
	    case "$VARLEN" in
		1)
		    VAR1="00"$1
		    ;;
		2)
		    VAR1="0"$1
		    ;;
		*)
		    VAR1=$1
		    ;;
	    esac
	    i=2
	    while [ -z $PINGABLE ]
	      do
              #NODE=`echo $MY_NODES | awk '{print $2}'`
	      NODE=`echo $MY_NODES | cut -d " " -f $i`
              #echo "ping -c 1 -q -W 5 $NODE|grep errors|wc -l"
	      PINGABLE=`ping -c 1 -q -W 5 $NODE|grep errors|wc -l`
	      i+=2
	    done
	    MYNODE=`pdsh -w $NODE shell -c "node info" |grep Up|grep -v Any|grep " $VAR1 "| awk '{print $9}'`
            #echo $MYNODE
	    if [ -z $MYNODE ]
		then
		MYNODE=`pdsh -w $NODE shell -c node|grep "Node\[\`echo $VAR1|sed "s/^[0]//"|sed "s/^[0]//"\`\]"| awk '{print $3}'|cut -d "=" -f 2|cut -d "," -f 1`
                echo "=========================================="
		echo "Seaquest Environment has not been started!"
	    fi
	    echo "=========================================="
	    echo "==  logical nid $1 ==> Node-name $MYNODE"
	    echo "==  ssh to $MYNODE"
	    echo "=========================================="
	    ssh $MYNODE

	else
	    echo ''
	    echo 'variable can not be more than 3 characters'
	    echo ''
	    exit 1
	fi
    else
	echo ''
	echo 'invalid nid, nid can only be numeric'
	echo ''
	exit 1
    fi
else
    echo 'USAGE "sqssh <nid>" to ssh to the physical node'
fi

