#!/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos72L src/bos/usr/lib/nim/methods/nimstat.sh 1.2 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2018 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 

#---------------------------- module globals    --------------------------------
#-------------------------------------------------------------------------------
PATH=.:/usr/sbin:/usr/bin:/bin
export PATH=$PATH

nquery=""
nodes=""
pid=$$

#---------------------------- function defines    ------------------------------
#-------------------------------------------------------------------------------
function cleanup {

    #clean up tables
    rm -f /var/tmp/*_nimstat_refcodes.$pid
    rm -f /var/tmp/*_nimstat_states.$pid
}

function err_cleanup {

    trap "" 1 2 11 15
    cleanup

    exit 1
}

function query_all_lpars {

	cec_list=`lsnim -t cec |awk '{print $1|"sort"}'`
	cec_count=0
	set -A cecs

	#put the list of cecs into an array.
	echo "$cec_list" | while read cec
	do
		[[ $cec != "" ]] && cecs[$cec_count]=$cec
		(( cec_count = cec_count + 1 ))
	done

	#iterate through the list of cecs we have gotten
	for cec_name in ${cecs[@]}
	do
		#get refcode info using nimquery with -r flag
		nim_qr=`nimquery -n $cec_name -r 2>/dev/null`
		#if nimquery fails skip over processing this cec
		if [[ $? -ne 0 ]]; then
			dspmsg -s 1 cmdnim.cat 37 '0042-037 %s: the state of \"%s\" prevents this operation\n\tfrom succeeding\n' "nimstat" $cec_name
			echo "\n"
			continue
		fi

		#this awk will sort by lpar_names and get their refcode staus
		led_codes=`echo "$nim_qr" | awk -F',' '{print $1, $4}' | sort  2>/dev/null`
		count=0
		leds=""
		#loop through each lpar on the cec and store their refcode info
		echo "$led_codes" | while read line
		do
			ref_code=`echo $line | awk -F'=' '{print $3}'`
			[[  -z "$ref_code" ]] && ref_code="blank"
			leds[$count]=$ref_code
			(( count = count + 1 ))
		done # led codes

		#get lpar's name in state info via nimquery (with no -r flag)
		nim_q=`nimquery -n $cec_name 2>/dev/null`
		#if nimquery fails skip over processing this cec
		if [[ $? -ne 0 ]]; then
			dspmsg -s 1 cmdnim.cat 37 '0042-037 %s: the state of \"%s\" prevents this operation\n\tfrom succeeding\n' "nimstat" $cec_name
			echo "\n"
			continue
		fi

		name_codes=`echo "$nim_q" | awk -F',' '{print $1, $2, $4}' | sort 2>/dev/null`
		padding="============================================="
		(( pad_len = 48 - ${#cec_name}))
		printf "%.20s %s %s %.${pad_len}s\n" "$padding" "CEC" "$cec_name" "$padding"
		printf "%-30s %-8s %-7s %-15s %-10s\n" "LPARNAME" "LPARID" "POWER" "STATE" "LED"
		count=0
		name=""
		state=""
		power=""

		#iterate through lpars on cec, printing out their status'
		#add LED info as well. both lists are sorted by lpar_name so they will match up here
		echo "$name_codes" | while read line
		do
			name=`echo $line | awk -F'=' '{print $2}' | awk -F' ' '{print $1}'`
			identity=`echo $line | awk -F'=' '{print $3}' | awk -F' ' '{print $1}'`
			state=`echo $line | awk -F'=' '{print $4}'`
			power="off"
			[[ "$state" = *@(Running|Operating) ]] && power="on"
			printf "%-30s %-8s %-7s %-15s %-10s \n" "$name" "$identity" "$power" "$state" "${leds[$count]}"
			(( count = count + 1 ))
		done # nimcodes from nimquery
		echo "\n"
	done ## cec loop
}

function verify_mgmt_profiles {
#specific node name(s) given (this is also the fallthru for -v option)

	#process based on nim names using nimquery
	printf "%-30s %-15s %-15s %-10s\n" "NODENAME" "POWER" "STATE" "LED"
	for entry in $nodes
	do
		state="unknown"
		power="unknown"
		led="Unavailable"
		profile=`lsnim -a mgmt_profile $entry 2>/dev/null| awk '/ mgmt_profile1 /{print $0}'`

		if [[ -n $profile ]]; then
			led=`nimquery -n $entry -r -a filter=refcode 2>&1| awk '{ if (/rc=/) outp="invalid" ; else outp=$0 ; print outp ; exit }'`
			if [[ "$led" = "invalid" ]]; then
				state="invalid"
			else
				[[ -z "${led}" ]] && led="blank"
				state=`nimquery -n $entry -a filter=state 2>/dev/null`
				if [[ -z "${state}" ]]; then
					state="unknown"
				elif [[ ${state} = *@(Running|Operating) ]]; then
					power="on"
				else
					power="off"
				fi
			fi
		fi
		printf "%-30s %-15s %-15s %-10s\n" "$entry" "$power" "$state" "$led"
	done
}


#-------------------------------  MAIN  ---------------------------------------
#------------------------------------------------------------------------------

#signal catch
trap cleanup 0
trap err_cleanup 1 2 11 15

#set parameters from command line
while getopts Avx c; do
	case ${c} in

		A)	# query all cec lpars
			query_all_lpars
			exit 0
			;;

		v)	# verify mode (check profiles while querying)
			nquery="true"
			;;

		x)	# debug mode (for debugging)
			set -x
			for i in $(typeset +f)
			do
				typeset -ft $i
			done
			;;

		\?)	# unknown option
			echo "\nUsage:\tnimstat [ -A | { [-v] [node..] } ]"
			exit 1
			;;
	esac
done

shift $((OPTIND - 1))

node_args="$@"

#get list of system profiles
[[ -z $node_args ]] && nodes=`lsnim -t standalone | awk '{print $1|"sort"}'` || nodes="$node_args"

if [ "$node_args" ] || [ "$nquery" ]; then

	verify_mgmt_profiles $nodes

else
#go through list of nim standalone objects and generate a list of cec's

	cec_list=""
	for nim_obj in $nodes
	do
		new_cec=`lsnim -a mgmt_profile ${nim_obj} | awk '/ mgmt_profile1 /{print $5}'`
		[[ -n $new_cec ]] && cec_list="${new_cec} \n${cec_list}"
	done
	#sort the list of cec's and eliminate any duplicate entries
	cec_list=`echo $cec_list | sort -u`

	cec_count=0
	set -A cecs
	#put the list of cecs into an array.
	echo "$cec_list" | while read cec
	do
		if [[ $cec != "" ]]; then
			cecs[$cec_count]=$cec
			(( cec_count = cec_count + 1 ))
		fi
	done

	#reduce output using lookup tables
	for cec_name in ${cecs[@]}
	do
		nimquery -n $cec_name -r -a filter=lpar_name,lpar_id,refcode >/var/tmp/${cec_name}_nimstat_refcodes.$pid 2>/dev/null
		nimquery -n $cec_name -a filter=name,lpar_id,state >/var/tmp/${cec_name}_nimstat_states.$pid 2>/dev/null
	done

	printf "%-30s %-15s %-15s %-10s\n" "NODENAME" "POWER" "STATE" "LED"
	for entry in $nodes
	do
		state="unknown"
		power="unknown"
		led="Unavailable"
		profile=`lsnim -a mgmt_profile $entry 2>/dev/null| awk '/ mgmt_profile1 /{print $0}'`

		if [[ -n $profile ]]; then
			lpar_id=`echo $profile | awk '{print $4}'`
			cec=`echo $profile | awk '{print $5}'`
			led_row=`grep ",${lpar_id}," /var/tmp/${cec}_nimstat_refcodes.$pid 2>/dev/null`

			if [[ -z ${led_row} ]]; then
				state="invalid"
			else
				led=`echo ${led_row} | awk -F ',' '{print $3}'`
				[[ -z "${led}" ]] && led="blank"

				state_row=`grep ",${lpar_id}," /var/tmp/${cec}_nimstat_states.$pid`

				if [[ -n ${state_row} ]]; then
					state=`echo ${state_row} | awk -F ',' '{print $3}'`
					if [[ -z "${state}" ]]; then
						state="unknown"
					elif [[ ${state} = *@(Running|Operating) ]]; then
						power="on"
					else
						power="off"
					fi
				fi
			fi
		fi
		printf "%-30s %-15s %-15s %-10s\n" "$entry" "$power" "$state" "$led"
	done
fi

exit 0
