#!/bin/bash

# Set log and storcli_bin lnd lspci ocations
log='/var/log/MegaRAID.log';
if [[ -x /usr/local/eig_zabbix/sbin/raidcheck/bin/storcli64 ]]; then
	storcli_bin='/usr/local/eig_zabbix/sbin/raidcheck/bin/storcli64';
else
	echo "Cannot find storcli; Exiting."
	exit 1;
fi;
if [[ -x /sbin/lspci ]]; then
	lspci_bin='/sbin/lspci';
elif [[ -x /usr/bin/lspci ]]; then
	lspci_bin='/usr/bin/lspci';
else
	echo "Cannot find lspci; Exiting."
	exit 1;
fi;

# Check for MegaRAID hardware
if ! ${lspci_bin} | grep -q MegaRAID;then
	exit 1;
fi

OUT="$(mktemp -d)"
cd $OUT
for controller in $(${storcli_bin} /call/eall/sall show all |  grep -oP 'Controller = \d+' | awk '{print $3}'); do
	if [[ ! -f ${log}.c${controller} ]];then
			${storcli_bin} /c${controller} show termlog | head -n -4 | egrep -v -e Exit -e '^$' >> ${log}.c${controller}
		chmod 600 ${log}.c${controller}
	else
		# Check if last line of on-disk log simply exists in live fwterm log
		if ! ${storcli_bin} /c${controller} show termlog | head -n -4 |tr -dc '[:alnum:]\n'|egrep -v -e Exit -e '^$'|grep -qm1 "$(tail -n 1 ${log}.c${controller}|tr -dc '[:alnum:]\n')"; then
			# If last line does not match anything in fwterm log, append whole fwterm log dump to on-disk log
			${storcli_bin} /c${controller} show termlog | head -n -4 | egrep -v -e Exit -e '^$' >> ${log}.c${controller}
		else
			# If last line of log does exist in fwterm log, then append to the on-disk log only what exists after the match
			LAST=$(tail -n 1 ${log}.c${controller} | sed 's/[[:punct:]]\+/\\&/g;s/[ \t]\+/\\&/g;s/\\\((\|)\)/\1/g')
			${storcli_bin} /c${controller} show termlog | head -n -4 | sed "1,/$LAST/d" | egrep -v -e Exit -e '^$' >> ${log}.c${controller}
		fi
	fi
done

if [ -n $OUT ]; then
	rm -rf $OUT
fi
cd

