#!/bin/bash


# This will be called on LSI based raidcontrollers and accesses
# the SMART data of SATA disks attached to a SAS Raid HBA via
# SCSI protocol interface.


#echo '<<<smart_ctl>>>'
#cat /etc/check_mk/smartctl/smart_temperature_latest
#exit 0

megaraid_info()
{

    #PDINFO=$(MegaCli -PDlist -a0)
    if [ -z "$1" ]; then
                PDINFO=$(megacli -PDlist -a0)
    else
                PDINFO=$($1 -PDlist -a0)
    fi

    echo "$PDINFO" | \
    while read line ; do
        case "$line" in
           # FIRST LINE
           "Enclosure Device ID"*) #Enclosure Device ID: 252
            ENC=$( echo "$line" | awk '{print $4}')
                  unset SLOT LOG_DEV_ID VEND MODEL
        ;;
        "Slot Number"*)  #Slot Number: 7
            SLOT=$( echo "$line" | awk '{print $3}')
        ;;
        # Identify the logical device ID. smartctl needs it to access the disk.
        "Device Id"*)    #Device Id: 19
            LOG_DEV_ID=$( echo "$line" | awk '{print $3}')
        ;;
        "PD Type"*)      #PD Type: SATA
            VEND=$( echo "$line" | awk '{print $3}')
        ;;
        # This is the last value, generate output here
        "Inquiry Data"*)
         #Inquiry Data: WD-WCC1T1035197WDC WD20EZRX-00DC0B0 80.00A80
            # $4 seems to be better for some vendors... wont be possible to get this perfect.
            MODEL=$( echo "$line" | awk '{print $3}')
            #echo "${MEGARAID_DEV#/dev/}_${LOG_DEV_ID}, $ENC, $SLOT, $VEND, $MODEL"
	    ## IF style is classic
            # /dev/sdc ATA SAMSUNG_SSD_830   5 Reallocated_Sector_Ct   0x0033   100   100   010    Pre-fail  Always       -
            #smartctl -d megaraid,${LOG_DEV_ID} -v 9,raw48 -a -A $MEGARAID_DEV | \
            #  grep Always  | egrep -v '^190(.*)Temperature(.*)'       | \
            #  sed "s|^|Enc${ENC}/Slot${SLOT} $VEND $MODEL |"
	    ## ELSE if style is SSD Like
            #smartctl -d megaraid,${LOG_DEV_ID} -v 9,raw48 -a -A $MEGARAID_DEV | awk  -v device="${MEGARAID_DEV#/dev/}_${LOG_DEV_ID}" '{ if ($1=="Vendor:") vendor=$2; else if($1=="Product:") product=$2; else if($1=="SMART") smart=$4; else if ($1=="Current") temperature=$4} END {print device"\t"vendor"\t"product"\t194\tTemperature_Celsius\t0x0002\t100\t100\t000\tOld_age\tAlways\t"temperature}'
            #smartctl -d megaraid,${LOG_DEV_ID} -v 9,raw48 -a -A $MEGARAID_DEV | awk  -v device="${MEGARAID_DEV#/dev/}_${LOG_DEV_ID}" '{ if ($1=="Vendor:") vendor=$2; else if($1=="Product:") product=$2; else if($1=="SMART") smart=$4; else if ($1=="Current") temperature=$4; else if ($2=="Trip") maxt=$4} END {print device"\t"vendor"\t"product"\t194\tTemperature_Celsius\t0x0002\t100\t100\t000\tOld_age\tAlways\t-\t"temperature"\t(Min/Max 15/"maxt")"}' 
            #smartctl -d megaraid,${LOG_DEV_ID} -v 9,raw48 -a -A $MEGARAID_DEV | awk  -v device="${MEGARAID_DEV#/dev/}_${LOG_DEV_ID}" '{ if ($1=="Vendor:") vendor=$2; else if($1=="Product:") product=$2; else if($1=="SMART") smart=$4; else if ($1=="Current") temperature=$4; else if ($2=="Trip") maxt=$4} END {print device"\t"vendor"\t"product"\t194\tTemperature_Celsius\t0x0002\t100\t100\t000\tOld_age\tAlways\t-\t"temperature}' 
            smartctl -d megaraid,${LOG_DEV_ID} -v 9,raw48 -a -A $MEGARAID_DEV | awk  -v device="${MEGARAID_DEV#/dev/}_${LOG_DEV_ID}" '{ if ($1=="Vendor:") vendor=$2; else if($1=="Product:") product=$2; else if($1=="SMART") smart=$4; else if ($1=="Current") temperature=$4; else if ($2=="Trip") maxt=$4} END {print device" "vendor" "product" 194 Temperature_Celsius 0x0002 100 100 000 Old_age Always - "temperature" (Min/Max 15/"maxt")"}' 
            #smartctl -d megaraid,${LOG_DEV_ID} -v 9,raw48 -a -A $MEGARAID_DEV | awk  -v device="${MEGARAID_DEV#/dev/}_${LOG_DEV_ID}" '{ if ($1=="Vendor:") vendor=$2; else if($1=="Product:") product=$2; else if($1=="SMART") smart=$4; else if ($1=="Current") temperature=$4; else if ($2=="Trip") maxt=$4} END {print device" "vendor" "product" 194 Temperature_Celsius 0x0002 100 100 000 Old_age Always - "temperature}' 
            ;;
            esac
       done
}


# Only handle always updated values, add device path and vendor/model
if which smartctl > /dev/null 2>&1 ; then
    #
    # if the 3ware-utility is found
    # get the serials for all disks on the controller
    #
    if which tw_cli > /dev/null 2>&1 ; then
        # support for only one controller at the moment
        TWAC=$(tw_cli show | awk 'NR < 4 { next } { print $1 }' | head -n 1)
        
       # - add a trailing zero to handle case of unused slot
       #   trailing zeros are part of the device links in /dev/disk/by-id/... anyway
       # - only the last 9 chars seem to be relevant
       # (hopefully all this doesn't change with new kernels...)
        eval `tw_cli /$TWAC show drivestatus | grep -E '^p[0-9]' | awk '{print $1 " " $7 "0"}' | while read twaminor serial ; do
            twaminor=${twaminor#p}
            serial=${serial:(-9)}
            serial=AMCC_${serial}00000000000
            #echo "$serial=$twaminor"
        done`
    fi

    MEGARAID_DEV=""

    declare -A DONE
    echo '<<<smart_ctl>>>'
    for D in `echo /dev/disk/by-id/{scsi,ata,wwn}-* /dev/sg?`; do
        [ "$D" != "${D%scsi-\*}" ] && continue
        [ "$D" != "${D%ata-\*}" ] && continue
        [ "$D" != "${D%-part*}" ] && continue
        N=$(readlink $D)
        N=${N##*/}
	if [[ $D == /dev/sg* ]]; then
		N=${D##*/}
	fi

        if [ -r /sys/block/$N/device/vendor ]; then
            VEND=$(tr -d ' ' < /sys/block/$N/device/vendor)
        elif [ -r /sys/class/scsi_generic/$N/../../../*/vendor ]; then
            VEND=$(tr -d ' ' < /sys/class/scsi_generic/$N/../../../*/vendor)
        else
            # 2012-01-25 Stefan Kaerst CDJ - in case $N does not exist
            VEND=ATA
        fi

        ##Check if one of the device is MegaRaid or DELL (LSI Controller)
        if [ "$VEND" == "MegaRaid" ] || [ "$VEND" == "DELL" ]; then
	    MEGARAID_DEV=$D
	fi
 
        if [ -r /sys/block/$N/device/model ]; then
            MODEL=$(sed -e 's/ /_/g' -e 's/_*$//g' < /sys/block/$N/device/model)
	elif [ -r /sys/class/scsi_generic/$N/../../../*/model ]; then
	    MODEL=$(tr -d ' ' < /sys/class/scsi_generic/$N/../../../*/model)
        else
            MODEL=$(smartctl -a $D | grep -i "device model" | sed -e "s/.*:[ ]*//g" -e "s/\ /_/g")
        fi
        # Excluded disk models for SAN arrays or certain RAID luns that are also not usable..
        if [ "$MODEL" = "iSCSI_Disk" ] || ["$MODEL" = "LOGICAL_VOLUME" ]; then
            continue
        fi

        # Avoid duplicate entries for same device
        if [ "${SEEN//.$N./}" != "$SEEN" ] ; then
            continue
        fi
        SEEN="$SEEN.$N."

        # strip device name for final output
        #echo $D
        if [[ $D == *by-id/scsi* ]]; then
        	DNAME=${D#/dev/disk/by-id/scsi-}
        fi
        if [[ $D == *by-id/ata* ]]; then
        	DNAME=${D#/dev/disk/by-id/ata-}
        fi
        if [[ $D == *by-id/wwn* ]]; then
        	DNAME=${D#/dev/disk/by-id/wwn-}
        fi
        if [[ $D == /dev/sg* ]]; then
                DNAME=${D#/dev/}
        fi

        # 2012-01-25 Stefan Kaerst CDJ - special option in case vendor is AMCC
        CMD=
        if [ "$VEND" == "AMCC" -a -n "$TWAC" ]; then
            DNAME=${DNAME#1}
            [ -z "${!DNAME}" ] && continue
            CMD="smartctl -d 3ware,${!DNAME} -v 9,raw48 -A /dev/twa0"
            # create nice device name including model
            MODEL=$(tw_cli /$TWAC/p${!DNAME} show model | head -n 1 | awk -F= '{ print $2 }')
            MODEL=${MODEL## }
            MODEL=${MODEL// /-}
            DNAME=${DNAME#AMCC_}
            DNAME="AMCC_${MODEL}_${DNAME%000000000000}"
	elif [[ $D == /dev/sg* && ! $VEND = "ATA" ]]; then
	    CMD="smartctl -d sat+scsi -v 9,raw48 -A $D"
	elif [[ $D == /dev/sg* && $VEND = "ATA" ]]; then
	    continue
        elif [ "$VEND" != "ATA" ] ; then
            TEMP=
            # create temperature output as expected by checks/smart_ctl
            # this is a hack, TODO: change checks/smart_ctl to support SCSI-disks
            #echo smartctl -i -A $D
            eval `smartctl -d scsi -i -A $D | while read a b c d e ; do
        	[ "$a" == Serial ] && echo SN=$c
        	[ "$a" == Current -a "$b" == Drive  -a "$c" == Temperature: ] && echo TEMP=$d
            done`
            [ -n "$TEMP" ] && CMD="echo 194 Temperature_Celsius 0x0000 000 000 000 Old_age Always - $TEMP (0 0 0 0)"
            DNAME="${VEND}_${MODEL}_${SN}"
        else
        # do not force ata channel. Let smartcl to recognize it via the default "auto" command.
            #CMD="smartctl -d ata -v 9,raw48 -A $D"
            CMD="smartctl -v 9,raw48 -A $D"
        fi

        [ -n "$CMD" ] && $CMD | grep Always | egrep -v '^190(.*)Temperature(.*)' | sed "s|^|$DNAME $VEND $MODEL |"

    done 2>/dev/null

       

    # Call MegaRaid submodule if conditions are met
    if type MegaCli >/dev/null ; then
        MegaCli_bin="MegaCli"
    elif type MegaCli64 >/dev/null ; then
        MegaCli_bin="MegaCli64"
    elif type megacli >/dev/null ; then
        MegaCli_bin="megacli"
    else
        MegaCli_bin="unknown"
    fi

    TIME_DATE=`date +%S%M%H_%d%m%Y`

    ## do not run another smartctl if smartctl is running.
    SMARTCTL_PID=`ps axf | grep smartctl | grep -v grep | awk '{print $1}'`
    if [ "$SMARTCTL_PID" == "" ]; then
	    ## Move all previous files to smart_temperature_latest
	    for i in `ls -t /etc/check_mk/smartctl/smart_temperature.* 2>> /dev/null`; do mv $i /etc/check_mk/smartctl/smart_temperature_latest; done

	    if [ -e "/etc/check_mk/smartctl/smart_temperature_latest" ]; then
		cat /etc/check_mk/smartctl/smart_temperature_latest
	    fi
	   
	    if [ "$MegaCli_bin" != "unknown" ]; then
		megaraid_info "$MegaCli_bin" >> /etc/check_mk/smartctl/smart_temperature.$TIME_DATE &
	    fi
    else
	    if [ -e "/etc/check_mk/smartctl/smart_temperature_latest" ]; then
                cat /etc/check_mk/smartctl/smart_temperature_latest
            fi
    fi

fi


