#!/bin/bash
#
# Monitor state of the Adaptec RAID model 52445 and send email on error
#
# The script uses files /usr/sbin/arcconf and /usr/sbin/hrconf which
# can be copied from RPM file asm_linux_x64_v5_20_17414.rpm.
#
# The script and the binaries need following libraries for operation:
# libstdc++5, coreutils
#
# It is advisable to set up the script to run each hour from cron
#
# Author: Arie Skliarouk <skliarie@gmail.com>
#
# Version history:
#
# 0.02	Extracted from the package because adaptec binaries can not be
#	redistributed.
#
# 0.01	First release as part of the adaptec-utils_0.0.1_amd64.deb package
#

TITLE="Adaptec 52445 Raid Status:"
MAILTO=$1
if [ -z "$MAILTO" ];
then
    MAILTO=root
fi

RAID=/var/tmp/adaptec52445.$$

/usr/sbin/arcconf getconfig 1 al > $RAID

MSG=""
CTRLSTAT="$(grep "Controller Status" $RAID| cut -d\: -f2)"
CTRLSTAT=$(echo $CTRLSTAT)
[ "$CTRLSTAT" != "Optimal" ] && MSG="$MSG\nController Status is not Optimal"

CTRLBATINFO="$(grep -A 2 "Controller Battery" $RAID|grep "Status"|cut -d\: -f2)"
CTRLBATINFO=$(echo $CTRLBATINFO)
if [ "$CTRLBATINFO" != "Optimal" ]
then
  if [ "$CTRLBATINFO" != "Charging" ];
  then
    MSG="$MSG\nController Battery is not Optimal"
  else
    # Battery status is Charging"
    CAPACITY="$(grep "Capacity remaining" $RAID|cut -d\: -f2|awk '{print $1}')"
    # Verify that "Capacity remaining" is above 90%"
    if [ "$CAPACITY" -lt 90 ];
    then
      MSG="$MSG\nController Battery has less than 90% of charge"
    fi
  fi
fi

CTRTEMP="$(grep "Temperature" $RAID| cut -d\: -f2|awk '{print $5}')"
CTRTEMP=$(echo $CTRTEMP)
[ "$CTRTEMP" != "(Normal)" ] && MSG="$MSG\nController Temperature is not Normal"

let iLOGICALDEV=0
grep "Status of logical device" $RAID | cut -d\: -f2 | while read STATUS; do
  [ "$STATUS" != "Optimal" ] && MSG="$MSG\nStatus of logical device $iLOGICALDEV not optimal"
  let iLOGICALDEV++
done

let iLOGICALDEV=0
grep "Failed stripes" $RAID| cut -d\: -f2 | while read STATUS; do
  [ "$STATUS" != "No" ] && MSG="$MSG\nFailed stripes on device $iLOGICALDEV"
  let iLOGICALDEV++
done

let iDEVICE=0
grep "Device #" $RAID | while read DEVICE; do
  STATUS="$(grep -A 2 "$DEVICE" $RAID | tail -1 | cut -d\: -f2)"
  [ "$STATUS" != "Online" ] && MSG="$MSG\nDEVICE $DEVICE not online"
  let iDEVICE++
done

TTY="$(tty)"
if [ "$TTY" == "not a tty" ];
then
    if [ -n "$MSG" ];
    then
      (echo -e "$TITLE\n$MSG"; cat $RAID;) |
        mail -s "RAID WARNING from $HOSTNAME" $MAILTO
    fi
    rm $RAID
else
    echo -e "$TITLE\n$MSG"
    echo "See full status in file $RAID"
fi

exit 0

