#!/bin/bash

if [ -z $SPOOLDIR ]; then
    SPOOLDIR=/var/spool/statusd
fi

STF=$SPOOLDIR/smart-megaraid.status

function attr_ok()
{
		echo "$smartdata" | grep -oEi '^[0-9 ]{1,3} [a-z\_\-]*[ \t]*0x[a-f0-9]{4}[ \t]*[0-9]{3}[ \t]*[0-9]{3}[ \t]*[0-9]{3}[ \t]*(Pre-fail|Old_age)[ \t]*(Always|Offline)[ \t]*[a-z\_\-]*[ \t]*[0-9]*' | while read ID ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE; do
			case $ATTRIBUTE_NAME in
				'Current_Pending_Sector')
					if [ -n "$RAW_VALUE" -a $RAW_VALUE -gt 0 ]; then
						echo -n "pendingsector"
					fi
				;;

				'Pending_Sector_Count')
					if [ -n "$RAW_VALUE" -a $RAW_VALUE -gt 0 ]; then
						echo -n "pendingsector"
					fi
				;;

				'Wear_Leveling_Count')
					if [ -n "$VALUE" -a $VALUE -lt 25 ]; then
						echo -n "wear"
					fi
				;;

				'Media_Wearout_Indicator')
					if [ -n "$VALUE" -a $VALUE -lt 25 ]; then
						echo -n "wear"
					fi
				;;
			esac
		done
}

function smarts()
{

	smart_list=`smartctl --scan 2>/dev/null | awk '{print $1 ";" $3}'`

	if [ -z "$smart_list" ]; then
		echo "No disk found"
		return
	fi

	wwn_list=''

	for drv in $smart_list; do
		drive_dev=${drv%%;*}
		drive_type=${drv##*;}

		case $drive_type in
			ata)
				ts=''
			;;
			scsi)
				ts=''
			;;
			*)
				ts="-d $drive_type"
			;;
		esac

		smartdata=`smartctl -n standby -a $drive_dev $ts 2>/dev/null`
		xc=$?
		if [ "$xc" != "2" ]; then

			WWN=`echo "$smartdata" |grep -i '\(wwn device id\|logical unit id\|eui-64\)' |tr -d ' ' |grep -oEi '[a-f0-9]{16}'`

			if [ -z "$WWN" ]; then
				WWN='UNKNOWN'
			fi

			if ! [[ $wwn_list =~ "$WWN" ]]; then

				if [ "$WWN" != 'UNKNOWN' ]; then
					wwn_list="$wwn_list $WWN"
				fi
				ec=''

				FAIL=0
				for mask in 8 16 32 128; do
					xca=$(($xc & $mask))
					if [ $xca -gt 0 ]; then
						FAIL=1
						ec="$ec fail-${xc}"
					fi
				done

				attr_test=`attr_ok`
				if [ -n "$attr_test" ]; then
					FAIL=1
					ec="$ec $attr_test"
				fi

				if [ "$FAIL" == "1" ]; then
					echo -n "[$drive_dev($drive_type):$ec]"
				fi
			fi
		fi
	done
}

if [ "$1" != "cron" -a -f $STF ]; then
    SMTS=`cat $STF`
else
    SMTS=`smarts`
    echo -n "$SMTS" >$STF
fi
if [ "x$SMTS" != "x" ]; then
	echo "$SMTS"
	exit 1
else
	echo "OK"
	exit 0
fi
