#!/usr/local/bin/bash
 
# e-mail variables
FROM=zpool@tingvold.com
TO=joachim@tingvold.com
SUBJECT="'zpool scrub'-status"
BODY=""

ERROR=0
SEP=" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "
 
# commands & configuration
ZPOOL=/sbin/zpool
SENDEMAIL=/usr/local/bin/sendEmail

# print a message
function _log {
    DATE="`date +"%Y-%m-%d %H:%M:%S"`"
    # add message to e-mail body
    BODY="${BODY}$DATE: $1\n"
}
 
# find all pools
pools=$($ZPOOL list -H -o name)
 
# for each pool
for pool in $pools; do
    # start scrub for $pool
    _log "starting scrub on $pool"
    zpool scrub $pool
    RUNNING=1
    # wait until scrub for $pool has finished running
    while [ $RUNNING = 1 ];     do
        # still running?
        if $ZPOOL status -v $pool | grep -q "scrub in progress"; then
            sleep 60
        # not running
        else
            # finished with this pool, exit
            _log "scrub ended on $pool"
            _log "`$ZPOOL status -v $pool`"
            _log "$SEP"
            RUNNING=0
            # check for errors
            if ! $ZPOOL status -v $pool | grep -q "No known data errors"; then
                _log "data errors detected on $pool"
                ERROR=1
            fi
        fi
    done
done
 
# change e-mail subject if there was error
if [ $ERROR = 1 ]; then
    SUBJECT="${SUBJECT}: ERROR(S) DETECTED"
fi
 
# send e-mail
sendemail -f $FROM -t $TO -u "$SUBJECT" -m "$BODY" -s smtp.domeneshop.no:587 -xu xxxx -xp yyyy