#!/bin/env bash
######################
#
# this script is used to send an email with some
# datas about the raid and the smart status
#
#####################
mail_path=`whereis mail |cut -d" " -f 2`
mdadm_path=`whereis mdadm |cut -d" " -f 2`
smartctl_path=`whereis smartctl |cut -d" " -f 2`
sed_path=`whereis sed |cut -d" " -f 2`
smartfile_old=/tmp/smart_check.old
smartfile_new=/tmp/smart_check.new
report_file=/tmp/smart_report
email=foo@bar
raid=1
smart=1
mail=1

function check_raid ()
{
# check each array
for array in $md; do
	# failed device ?
        status=`$mdadm_path --detail $array | grep 'Failed Devices' | cut -d":" -f 2` 
        if [ $status != 0 ]; then
echo paszero
		# wich one ?
                failed_disk=`$mdadm_path --detail $array | grep faulty | awk '{ print $7 } '` 
                echo -e "FAULTY DISK $failed_disk in array $array !!\n" >> $report_file
        fi
done
}

function check_smart ()
{
# chech each /dev/sdX
for disk in $sd; do
	item_nb=`$smartctl_path -a $disk | grep Pre-fail | wc -l`
	disk_name=`echo "$disk" | cut -d "/" -f3`
	if [ -f $smartfile_new$disk_name ];then # at least the second run? here we go
		mv $smartfile_new$disk_name $smartfile_old$disk_name
	        $smartctl_path -a $disk | grep Pre-fail | awk '{ print $2, $4, $6}' > $smartfile_new$disk_name
	        diff -q $smartfile_old$disk_name $smartfile_new$disk_name &> /dev/null # evolution since the last run
	        if [ "$?" != "0" ];then
	                i=1
	                while [ "$i" -le "$item_nb" ]; do # compare each item in the files
	                        line_old=`$sed_path -ne "$i p" $smartfile_old$disk_name`
	                        line_new=`$sed_path -ne "$i p" $smartfile_new$disk_name`
	                        if [ "$line_old" != "$line_new" ]; then
	                                item=`echo $line_old | awk '{ print $1 }'`
	                                value_old=`echo $line_old | awk '{ print $2 }' | $sed_path 's/^0\+//'`
	                                value_new=`echo $line_new | awk '{ print $2 }'| $sed_path 's/^0\+//'`
					if (( $value_new < $value_old ));then
						threshold=`echo $line_new | awk '{ print $3 }'`
		                                echo -e "$disk :\t $item errors changed from $value_old to $value_new \t###\t threshold = $threshold" >> $report_file
					fi
	                        fi
			let i++
	                done
		fi
	else # first run -> first data
		$smartctl_path -a $disk | grep Pre-fail | awk '{ print $2, $4}' > $smartfile_new$disk_name
	fi
done
}

if [ -f $report_file ]; then rm $report_file; fi
if [ `id -u` != 0 ]; then echo "should be run as root" && exit 1 ; fi

# launch appropriate function if activated
if [ -e "/dev/md1" ] && [ $raid = 1 ];then
	md=`ls -1 /dev/md?`
	check_raid
fi

if [ -e "/dev/sda" ] && [ $smart = 1 ];then
	sd=`ls -1 /dev/sd?`
	check_smart
fi

if [ -f $report_file ] && [ $mail = 1 ];then
	cat $report_file | $mail_path -s "DISK AND RAID HEALTH STATUS" $email
fi
