#!/bin/bash

: << =cut

=head1 LICENSE

GNU General Public License, version 2 or any later version

 #%# family=manual
 #%# capabilities=autoconf

=cut

## Tunable parameters with defaults
MYSQL="${mysql:-/usr/bin/mysql}"
#MYSQLOPTS="${mysqlopts:---user=munin --host=localhost}"
MYSQLOPTS="${mysqlopts:---user=zonem --password=jx5nfE6s --host=localhost}"

# Convenient variables
MEXEC="$MYSQL $MYSQLOPTS --batch --skip-column-names --database=information_schema --execute"

## No user serviceable parts below
print_config() {
    echo 'graph_title ZM Alarm stats'
    echo 'graph_args --base 1000'
    echo 'graph_vlabel Pixel'
    echo 'graph_category Zoneminder'
    echo 'graph_info ZM Events stats'
    echo 'alarm.label alarmed pixels'
    echo 'alarm.draw AREA'
    echo 'alarm.type GAUGE'
    echo 'filter.label filtered pixels'
    echo 'filter.draw AREA'
    echo 'filter.type GAUGE'
    echo 'blob.label blob pixels'
    echo 'blob.draw AREA'
    echo 'blob.type GAUGE'
    exit 0
}

print_data() {
    get_data | xargs -r printf "alarm.value %s\nfilter.value %s\nblob.value %s\n"
}

check_autoconf() {

    # Check client
    if [ ! -x $MYSQL ]; then
	echo "no ($MYSQL not executable)"
	return 0
    fi

    # Check server
    $MEXEC "select(1);" | \
	while read res; do
	    case $res in
		1)
		# All is well
		    ;;
		*)
		    echo "no (Could not contact mysql server)"
		    return 0
		    ;;
	    esac
    done

    # Default, say "yes" and hope for the best
    echo "yes"
}


# wrapper
get_data() {
# $MEXEC "select SUM(Stats.AlarmPixels), SUM(Stats.FilterPixels), SUM(Stats.BlobPixels) FROM zm.Stats AS Stats JOIN zm.Events AS Events ON Stats.EventId=Events.Id WHERE Events.EndTime BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW();"
RESULT=$($MEXEC "select SUM(Stats.AlarmPixels), SUM(Stats.FilterPixels), SUM(Stats.BlobPixels) FROM zm.Stats AS Stats JOIN zm.Events AS Events ON Stats.EventId=Events.Id JOIN zm.Frames AS Frames ON Stats.FrameId=Frames.FrameId WHERE (Events.EndTime BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW() OR Events.EndTime IS NULL) AND Frames.TimeStamp BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW();")
  if [ "$RESULT" == "NULL	NULL	NULL" ]
  then
    echo "0 0 0"
  else
    echo "$RESULT"
  fi
}

# Parse arguments, run correct function
case $1 in
    "autoconf")
	check_autoconf
	;;
    "config")
	print_config
	;;
    "test")
	get_data
        ;;
    *)
	print_data
	;;
esac