#!@@GOODSH@@
# -*- sh -*-

: << =cut

=head1 NAME

courier_ - plugin to graph courier logins and logouts

=head1 APPLICABLE SYSTEMS

Any system with a courier imap/pop3 server and logtail installed

=head1 CONFIGURATION

The configuration variables are:

 logtail - path to the logtail script
 logfile - log file from courier
 service - which courier service to graph

Service names for courier are "imaplogin" and "courierpop3login".
Good symlink names for this plugin is "courier_imaplogin" and
"courier_courierpop3login", which will set the "service" environment
variable to "imaplogin" and "courierpop3login", respectively.

The default configuration is:

 [courier_*]
  env.logtail /usr/sbin/logtail
  env.logfile /var/log/mail.log
  env.service <Whatever follows "courier_" in the file name>

=head1 MAGIC MARKERS

 #%# family=contrib
 #%# capabilities=autoconf

=head1 BUGS

None known

=head1 AUTHOR

# Coypright Micah Anderson <micah@riseup.net>
# Jan 22, 2005

=head1 LICENSE

Unknown

=cut

# Set the location of the courier logs
COURIER_LOG=${logfile:-/var/log/mail.log}
SERVICE=${service:-$(basename "$0" | sed 's/^courier_//g')}
OFFSET_FILE=${MUNIN_PLUGSTATE}/courier_${SERVICE}.offset
LOGTAIL=${logtail:-/usr/sbin/logtail}


case $1 in
    autoconf|detect)
    if [ -f "$COURIER_LOG" ] &&  [ -x "$LOGTAIL" ]; then
	# Makes no sense for wildcard plugin to autoconf to yes
	# unless you can provide suggestions.
	echo no
	exit 0
    else
	echo "no (either $COURIER_LOG was not found, or logtail was not in your path)"
	exit 0
    fi
    ;;
    config)
    cat <<EOF
graph_title Courier $SERVICE Connections
graph_vlabel Number of Connections
graph_total Total
connection.label connections
disconnected.label disconnections
login.label logins
logout.label logouts
EOF
    exit 0
    ;;
esac

ARGS=0
"$LOGTAIL" /etc/hosts 2>/dev/null >/dev/null
if [ $? = 66 ]; then
    if [ -z "$logtail" ]; then
        ARGS=1
    fi
fi

TEMP_FILE=$(@@MKTEMP@@ munin-courier.XXXXXX)

if [ -z "$TEMP_FILE" ] || [ ! -f "$TEMP_FILE" ]; then
    exit 3
fi

if [ "$ARGS" != 0 ]; then
    "$LOGTAIL" -f "${COURIER_LOG}" -o "${OFFSET_FILE}" | grep "$SERVICE" > "$TEMP_FILE"
else
    "$LOGTAIL" "${COURIER_LOG}" "${OFFSET_FILE}" | grep "$SERVICE" > "$TEMP_FILE"
fi
connection=$(grep Connection "$TEMP_FILE" | wc -l)
disconnected=$(grep DISCONNECTED "$TEMP_FILE" | wc -l)
login=$(grep LOGIN "$TEMP_FILE" | wc -l)
logout=$(grep LOGOUT "$TEMP_FILE" | wc -l)

rm "$TEMP_FILE"

echo "connection.value ${connection}"
echo "disconnected.value ${disconnected}"
echo "login.value ${login}"
echo "logout.value ${logout}"
