#!/bin/sh
#
# This tool fixes a corrupted midplane FRU using the good
# midplane FRU content. The midplane recovery feature
# only applies to Carnegie platform only.
#

. /usr/local/bin/sig_catcher

usage() {
	echo "Usage: carneige_fix_csum_mp.sh"
}


if [ $# -gt 1 ]; then
	usage
	exit 1
fi


if [ ! -f /var/run/Carnegie ]; then
	# non-Carnegie platforms
	echo "Request not applicable on this platform"
	exit 0
fi

# Carnegie platform only
TMP_FRU_FILE="/tmp/fixCsumFruFile"
goodFruCnt=0
badFruCnt=0
failChkSumCnt=0
err1="checksum"
err2="access"
err3="absent"
err4="general"
csumFruNo=0
validFruNo=0

echo
echo "Current midplane FRUs summary"

# only loop through FRU 1 and 2 for both midplane FRUs
for mpFru in 1 2
do
	# display FRU content
	/usr/local/bin/fruprog show $mpFru

	# output to temporary file
	/usr/local/bin/fruprog show $mpFru > $TMP_FRU_FILE

	# Detect MP FRU with checksum error using counters
	if `cat $TMP_FRU_FILE | grep -q -e $err1` ; then
		failChkSumCnt=`expr $failChkSumCnt + 1`
		csumFruNo=$mpFru
	fi

	# Detect bad and good MP FRUs by tracking with counters
	if `cat $TMP_FRU_FILE | grep -q -e $err1 -e $err2 -e $err3 -e $err4` ; then
		badFruCnt=`expr $badFruCnt + 1`
	else
		# healty MP FRU
		goodFruCnt=`expr $goodFruCnt + 1`
		validFruNo=$mpFru
	fi
done

rm -f $TMP_FRU_FILE

# no issue found
if [ $goodFruCnt == 2 ] ; then
	echo "Both midplane FRUs are healthy. No action taken."
	echo
	exit 1
fi

# both midplane FRUs have checksum error
if [ $failChkSumCnt == 2 ] ; then
	echo "Detected checksum errors on both midplane FRUs. Recovery not possible."
	echo
	exit 1
fi

# one or more midplane FRUs is not accessible
if [ $badFruCnt -gt $failChkSumCnt ] || [ $goodFruCnt == 0 ] ; then
	echo "Device not accessible on one or more midplane FRUs. Recovery not possible."
	echo
	exit 1
fi

# Reaching here means one good MP FRU and one bad checksum MP FRU
echo "Checksum error detected on midplane FRU$csumFruNo."
echo "Using midplane FRU$validFruNo content for recovery. Please wait ..."
echo

fruFieldLine=1

/usr/local/bin/fruprog dump $validFruNo |
while read line
do
	if [ $fruFieldLine != 7 ] ; then
		# Restore by using original content
		echo $line >> $TMP_FRU_FILE
	else
		# Set HAOSC back to default by clearing custom field
		echo >> $TMP_FRU_FILE
	fi
	fruFieldLine=`expr $fruFieldLine + 1`

	if [ $fruFieldLine -gt 7 ] ; then
		echo "yes" >> $TMP_FRU_FILE # Set up for commiting FRU
		break
	fi
done

# Restore the content to the bad MP FRU
/usr/local/bin/fruprog set $csumFruNo < $TMP_FRU_FILE > /dev/null;

echo "New midplane FRUs summary"

/usr/local/bin/fruprog show 1
/usr/local/bin/fruprog show 2

echo "Midplane FRU$csumFruNo is restored with default HAOSC setting."
echo

rm -f $TMP_FRU_FILE 
exit 1

