#!/bin/bash

# Set log and megacli_bin lnd lspci ocations
log='/var/log/MegaRAID.log';
if [[ -x /var/lib/zabbix/sbin/raidcheck/bin/MegaCli64 ]]; then
	megacli_bin='/var/lib/zabbix/sbin/raidcheck/bin/MegaCli64';
elif [[ -x /opt/MegaRAID/MegaCli/MegaCli64 ]]; then
	megacli_bin='/opt/MegaRAID/MegaCli/MegaCli64';
else
	echo "Cannot find MegaCli64; 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
if [[ ! -f ${log} ]];then
	${megacli_bin} fwtermlog dsply -a0 | egrep -v -e Exit -e '^$' >> ${log}
	chmod 600 ${log}
else
	# Check if last line of on-disk log simply exists in live fwterm log
	if ! ${megacli_bin} fwtermlog dsply -a0|tr -dc '[:alnum:]\n'|egrep -v -e Exit -e '^$'|grep -qm1 "$(tail -n 1 ${log}|tr -dc '[:alnum:]\n')"; then
		# If last line does not match anything in fwterm log, append whole fwterm log dump to on-disk log
		${megacli_bin} fwtermlog dsply -a0 | egrep -v -e Exit -e '^$' >> ${log}
	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} | sed 's/[[:punct:]]\+/\\&/g;s/[ \t]\+/\\&/g;s/\\\((\|)\)/\1/g')
		${megacli_bin} fwtermlog dsply -a0 | sed "1,/$LAST/d" | egrep -v -e Exit -e '^$' >> ${log}
	fi     
fi

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

