#!/bin/bash

# Plugin to monitor harddrive temperatures connected to a MegaRAID controller
# 
# Plugin must be ran as root so add these configuration in 
#   /etc/munin/plugin-conf.d/munin-node.
#
# [megacli*]
# user root
#
# -----------
# 2011-06-10 ver 1.0
# - initial version


# TODO
# - allow override of tool path via config

# 32-bit or 64-bit
if [[ $( uname -a | grep x86_64 ) ]]
then
    MEGACLI='/opt/MegaRAID/MegaCli/MegaCli64'
else
    MEGACLI='/opt/MegaRAID/MegaCli/MegaCli'
fi

if [[ ! -x $MEGACLI ]]
then
    echo "FATAL ERROR: $MEGACLI not found or not executable!"
    exit 1
fi

declare -a output

IFS=$'\n'
output=($($MEGACLI -PDList -aALL -NoLog | grep -E 'Inquiry Data:|Drive Temperature' | cut -f2 -d:))
unset IFS

# TODO
# - if array size is odd, there's a problem, exit?
output_size=${#output[*]}

if [ "$1" = "config" ]
then

    echo 'graph_title MegaCli HDD temperature'
    echo 'graph_args --base 1000 -l 0'
    echo 'graph_vlabel temp in °C'
    echo 'graph_category sensors'

    i=0
    while [[ $i -lt $output_size ]]
    do
        if [ $((i % 2)) -eq 0 ]
        then

            label=$( echo ${output[$i]} | perl -ne \
                's/^\s*|\s*$//; print;' )

            # TODO:
            # - add other brands??

            # remove brand name, just model and serial number
            label_graph=$( echo ${output[$i]} | perl -ne \
                's/SEAGATE|MAXTOR|WDC//i; s/^\s*|\s*$//; print;' )

            echo $(echo $label | tr ' ' _).label $label_graph
        fi

        (( i++ ))
    done

    exit 0
fi

# print label and corresponding value
# - even -> label
# - odd  -> value
i=0
while [[ $i -lt $output_size ]]
do
    if [ $((i % 2)) -eq 0 ]
    then
        label=$( echo ${output[$i]} | perl -ne 's/^\s*|\s*$//; print;' )
        echo -n $(echo $label | tr ' ' _).value
    else
        value=$( echo ${output[$i]} | cut -f1 -dC )
        echo " $value"
    fi

    (( i++ ))
done
