#!/bin/bash

if ! /sbin/lspci | grep -q MegaRAID;then
    exit 1;
fi
OUT="$(mktemp -d)"
cd $OUT
if [[ ! -f /var/log/MegaRAID.log ]];then
    /opt/MegaRAID/MegaCli/MegaCli64 fwtermlog dsply -a0 | egrep -v -e Exit -e '^$' >> /var/log/MegaRAID.log
    chmod 600 /var/log/MegaRAID.log
else
     LAST=$(tail -n 1 /var/log/MegaRAID.log | sed 's/[[:punct:]]\+/\\&/g;s/[ \t]\+/\\&/g;s/\\\((\|)\)/\1/g')
     CHECK=$(/opt/MegaRAID/MegaCli/MegaCli64 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)
         /opt/MegaRAID/MegaCli/MegaCli64 fwtermlog dsply -a0 | egrep -v -e Exit -e '^$' >> /var/log/MegaRAID.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.  
         /opt/MegaRAID/MegaCli/MegaCli64 fwtermlog dsply -a0 | sed "1,/$LAST/d" | egrep -v -e Exit -e '^$' >> /var/log/MegaRAID.log
     fi     
fi

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

