#!/bin/ash
 
#set -x

. /usr/local/bin/sig_catcher

FRU_LOG_DIR="/mnt/logs/fru"
NUM_FRUS=""
# SHOW_TYPE - this script only supports 2.  Other types are:
# 0=FRU_NORM_SHOW
# 1=FRU_NETAPP_FILE_SHOW
# 2=FRU_NETAPP_SHOW
# 3=FRU_IPMI_SHOW
SHOW_TYPE=2
CMD_RESULT=""
HAS_NON_IPMI_PARSER=0

# $1 -- num of the recent frulog to display per FRU
#    -- ALL if $1 is not specified
FRULOG_MAXCOUNT=0
if [ $# -gt 0 ] ; then
      FRULOG_MAXCOUNT=$1
fi

echo
NUM_FRUS=`ls $FRU_LOG_DIR | wc -w`
DIR_LIST=`ls $FRU_LOG_DIR | sort -g`

for n in $NUM_FRUS ; do
	for i in $DIR_LIST ; do
		cd $FRU_LOG_DIR/$i

		# Process FRU ID label

		if [ -f label ]; 
		then
			echo "`cat label`"
			echo
		else
			# Don't have label file, use FRU ID
			echo "FRU ID $i (missing FRU label)"
			echo
		fi

		# Check for non-IPMI parser.  If there is one, use it.
		# Otherwise, use IPMI parser.

		if [ -L parser ]; then
			ls -L parser &> /dev/null
			CMD_RESULT=$?
			if [ $CMD_RESULT -eq 0 ]; then
				HAS_NON_IPMI_PARSER=1 ; 
			fi
		fi

		# Check for missing log file

		if ! ls install:* &> /dev/null ;
		then
			echo "FRU log file is not available"
			echo
		else
			# Now process FRU log files
			count=0
			for j in $(ls -r $FRU_LOG_DIR/$i) ; do

				# if max frulog has reached, break;
				count=$(($count + 1))
				if [ $FRULOG_MAXCOUNT -gt 0 ] && [ $count -gt $FRULOG_MAXCOUNT ]; then
					break
				fi
				
				# Skip label and parser file if any 

				if [ "$j" != "label" ] && [ "$j" != "parser" ]; then

					# We have both IPMI and non-IPMI FRU format files
					# in the same directory.  We want to decode the 
					# non-IPMI format (*-raw-bin*) if we have a parser for 
					# it.  Otherwise, we need to skip that file.
					echo $j | grep ".*-raw.bin*"  > /dev/null
					CMD_RESULT=$?
					if [ $CMD_RESULT -eq 0 ] ; then

						# Files in non-IPMI format

						if [ $HAS_NON_IPMI_PARSER -eq 1 ]; then
							echo "$j"
							# The parser has the following format:
							# parser [param1, param2, ...] < $j
							# Put appropriate parameter for parser here
							# Example: parser $SHOW_TYPE < $j ;
							echo
						#else
							#echo "DBG: No parser for non-ipmi format"
						fi
					else
						# Files in IPMI format

						echo "$j"
						/usr/local/bin/ipmifruparser $SHOW_TYPE < $j
						echo
					
					fi
				fi
			done
		fi
	done
done
