#!/bin/sh

# vim: set ft=sh :
# -*- sh -*-

: << =cut

=head1 NAME

mpdstats_ - Munin plugin to monitor a MPD database

=head1 DEPENDENCIES

This plugin uses netcat(1) to communicate with the MPD daemon.

Tip: To see if it is already set up correctly, just run this plugin
with the parameter "autoconf". If you get a "yes", everything should
work like a charm already.

=head1 INSTALLATION

This wildcard plugin should be symlinked using one of these names:
mpdstats_artists, mpdstats_albums, mpdstats_songs

=head1 CONFIGURATION

No configuration should be required if run on the same server as
MPD. If the plugin is run from remote or in a non-default configuration,
please use the environment variables 'mpd_host' and 'mpd_port' to connect.

Also, if your netcat(1) binary is anywhere else than /bin/nc please define
it using the 'netcat' environment variable.

=head2 CONFIGURATION EXAMPLE

 [mpdstats_*]
  env.mpd_host 192.168.0.43
  env.mpd_port 6606
  env.netcat /usr/local/bin/nc

=head1 AUTHOR

Copyright (C) 2012 ToM <tom@leloop.org>

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 dated June,
1991.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf suggest

=cut



MPDHOST=${mpd_host:-localhost}
MPDPORT=${mpd_port:-6600}
NCBIN=${netcat:-/bin/nc}

#
# FUNCTIONS
#

do_autoconf () {
    case "$ACTION" in
        albums|artists|songs)
            ;;
        *)
            echo "no (not a valid symlink name, please read the plugin doc)"
            exit 1
            ;;
    esac

    if [ ! -x $NCBIN ] ; then
        echo "no ($NCBIN: not found or not executable)"
        exit 1
    fi

    echo version | $NCBIN -q 2 $MPDHOST $MPDPORT 1>/dev/null 2>&1
    if [ "$?" != 0 ] ; then
        echo "no (connection failed)"
        exit 1
    fi

    echo "yes"
    exit 0
}

#
# MAIN
#

SCRIPTNAME=${0##*/}
ACTION=${SCRIPTNAME##*_}

case "$1" in
    autoconf)
        do_autoconf
        ;;
    suggest)
        echo "$ACTION"
        exit 0
        ;;
    config)
        echo "graph_category MPD
graph_title $ACTION in the database
graph_info Number of $ACTION in the database.
graph_vlabel $ACTION in the db
graph_args --base 1000 -l 0
graph_scale no
$ACTION.type GAUGE
$ACTION.draw LINE2
$ACTION.label $ACTION"
        exit 0
        ;;
    *)
        printf "$ACTION.value "
        echo stats | $NCBIN -q 2 $MPDHOST $MPDPORT | awk " /^${ACTION}/ {print \$2}"
        ;;
esac
