#!/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 'multigraph zoneminder_alarm_stats_individual_'$1
    echo 'graph_title ZM Alarm stats for' $2
    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'
}

print_data() {
    get_data $1 $2 | xargs -r printf "multigraph zoneminder_alarm_stats_individual_%s%.s\nalarm.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();"
# $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() AND Frames.TimeStamp BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW();"
RESULT=$($MEXEC "select Monitors.Id, Monitors.Name, 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 JOIN zm.Monitors AS Monitors ON Events.MonitorId=Monitors.Id WHERE Monitors.Name=\"$2\" AND (Events.EndTime BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW() OR Events.EndTime IS NULL) AND Frames.TimeStamp BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW() GROUP BY Events.MonitorId;")
if [ "${RESULT[0]}" == "" ]
then
  echo "$1 $2 0 0 0"
else
  echo "$RESULT"
fi
}

# Parse arguments, run correct function
case $1 in
    "autoconf")
	check_autoconf
	;;
    "config")
	dbquery=$($MEXEC "select Id, Name FROM zm.Monitors;")
	args=( $( for i in $dbquery ; do echo $i ; done ) )
	for ((i=0; i<${#args[@]}; i+=2)); do
	    PROPERTY="${args[$i]}"
	    VALUE="${args[$i + 1]}"
	    print_config $PROPERTY $VALUE
	done
	;;
     "test")
        dbquery=$($MEXEC "select Id, Name FROM zm.Monitors;")
        args=( $( for i in $dbquery ; do echo $i ; done ) )
        for ((i=0; i<${#args[@]}; i+=2)); do
            PROPERTY="${args[$i]}"
            VALUE="${args[$i + 1]}"
            get_data $PROPERTY $VALUE
        done
	;;
    *)
	dbquery=$($MEXEC "select Id, Name FROM zm.Monitors;")
        args=( $( for i in $dbquery ; do echo $i ; done ) )
        for ((i=0; i<${#args[@]}; i+=2)); do
            PROPERTY="${args[$i]}"
            VALUE="${args[$i + 1]}"
            print_data $PROPERTY $VALUE
        done
        ;;
esac