#!/bin/bash

# Set log and megacli_bin lnd lspci ocations
log='/var/log/MegaRAID.log';
if [[ -x /usr/local/eig_zabbix/sbin/raidcheck/bin/MegaCli64 ]]; then
	megacli_bin='/usr/local/eig_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."
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
	LAST=$(tail -n 1 ${log} | sed 's/[[:punct:]]\+/\\&/g;s/[ \t]\+/\\&/g;s/\\\((\|)\)/\1/g')
	CHECK=$(${megacli_bin} fwtermlog dsply -a0 | sed "1,/$LAST/d")
	#CHECK will return !null if it matches the final line, setting it to the Exit code at the end of the MegaRAID output.  
	if [[ -z $CHECK ]];then
		#In the event that CHECK finds no match, thus printing nothing outside of the sed line, dump whole log.  (In case card truncates @ reboot or full)
		${megacli_bin} fwtermlog dsply -a0 | egrep -v -e Exit -e '^$' >> ${log}
	else
		#If CHECK returns the exit code, it will add nothing.  Otherwise, it will print the additional lines after the match sans Exit code.  
		${megacli_bin} fwtermlog dsply -a0 | sed "1,/$LAST/d" | egrep -v -e Exit -e '^$' >> ${log}
	fi     
fi

if test $(find ${log} -atime +30);then
	gzip -7 -S .$(date '+%m-%G').gz ${log}
fi
if [ -n $OUT ]; then
	rm -rf $OUT
fi
cd

