#!/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 Events stats'
    echo 'graph_args --base 1000'
    echo 'graph_vlabel Events stats'
    echo 'graph_category Zoneminder'
    echo 'graph_info ZM Events stats'
    echo 'total.label max. total Score'
    echo 'total.type GAUGE'
    echo 'avg.label max. avg Score'
    echo 'avg.type GAUGE'
    echo 'length.label max. length secs'
    echo 'length.type GAUGE'
    exit 0
}

print_data() {
    get_data | xargs -r printf "total.value %s\navg.value %s\nlength.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() {
	RESULT=$($MEXEC "select MAX(TotScore), MAX(AvgScore),MAX(Length) FROM zm.Events WHERE (Events.EndTime BETWEEN (NOW() - INTERVAL 5 MINUTE) AND NOW() OR Events.EndTime IS NULL);")
  if [ "$RESULT" == "" ]
  then
    echo "0 0 0"
  else
    echo "$RESULT"
  fi
}

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