#!/bin/sh

POOLDB=/opt/var/status.zfspools
CONFIG=/opt/etc/zpmon.conf

MAILFILE=/tmp/zpools.mailfile.zpmon
PLIST=/tmp/zpools.zpmon
NEWDB=/tmp/status.zfspools.zpmon
MAILCOMMAND="/usr/local/bin/php -f /opt/etc/send-file-utf8.php $0-`hostname` "

if [ -f $CONFIG ]; then
.	$CONFIG
fi

zpool status | grep 'pool:' > $PLIST
NUMPOOLS=`cat $PLIST | wc -l`

if [ "$NUMPOOLS" -lt 1 ]; then
	exit
fi

if [ -f $NEWDB ]; then
	rm $NEWDB
fi

if [ -f $MAILFILE ]; then
	rm $MAILFILE
fi

for PNO in `seq 1 $NUMPOOLS`; do
	POOL=`cat "$PLIST" | head -n $PNO | tail -n 1 | awk '{print $2;}'`
	STATE=`zpool status $POOL | grep 'state: ' | awk '{print $2;}'`
	echo "$POOL $STATE" >> $NEWDB
	PREVSTATE=`cat $POOLDB 2>/dev/null | grep ^"$POOL" | awk '{print $2;}'`
	if [ -z "$PREVSTATE" ]; then
		PREVSTATE=$STATE
	fi
	if [ "$STATE" != "$PREVSTATE" ]; then
		echo Pool $POOL state change: was $PREVSTATE, now $STATE\; >> $MAILFILE
	fi
done

cat $NEWDB > $POOLDB

if ! [ -z "$REPORT_FILE" ]; then
	cat $POOLDB > $REPORT_FILE
fi

rm -f $PLIST
rm -f $NEWDB

if [ -f $MAILFILE ]; then
	$MAILCOMMAND $MAILFILE
	rm $MAILFILE
fi

