#!/bin/sh

: << =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'
    echo 'graph_args --base 1000'
    echo 'graph_vlabel Events'
    echo 'graph_category Zoneminder'
    echo 'graph_info ZM Events'
    echo 'events.label Events'
    echo 'events.draw AREA'
    echo 'events.type COUNTER'
    exit 0
}

print_data() {
    get_data | xargs -r printf "events.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"
}

mysql_version() {
    $MEXEC "SELECT version();" | awk '{printf "%1.1f", $1}'
}


# wrapper
get_data() {
$MEXEC "SELECT MAX(Id) FROM zm.Events;"
}

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