#!/usr/local/bin/perl
#
# Copyright Telecom Finland 1998
#  Heikki Hannikainen <heikki.hannikainen@tele.fi>
#
# (this initial comment boilerplate by Matti Aarnio)
#
# This is ZMailer queue poller script to produce data poll results
# for the MRTG monitoring grapher utility
#
# This is intended to be run from under inetd(8) with following
# kind of parameter line:
#
#   mrtg-zmq  stream tcp nowait root /usr/sbin/tcpd /usr/local/sbin/mrtg-zmq
#
# It obviously needs adding "mrtg-zmq" into /etc/services (or equivalent
# NIS/NIS+ service), plus installing and configuring the TCP-Wrapper.
#
# How to do those is left as an excercise to the reader; the reader
# is assumed to be quite bright when s/he is playing with MRTG.
#
# The output is one line of space separates sequence of tokens -- numeric
# values in following order:
#
#  - router queue (by directory scan)
#  - transport queue (by directory scan)
#  - number of scheduler kids
#  - number of idle scheduler kids
#  - number of message files in transporter per scheduler's knowledge
#    (this should equal with transport queue, or be very close!)
#  - number of threads; different destination domains to be sent to
#  - number of recipients; sum of message counts per destinations
#  - Triplets of:
#     - channel/host selector
#     - number of threads (different destination domains)
#     - sum of number of messages in all these group
#
# Only the first seven (7) fields are there always, and the triplets
# may or may not exist, plus their order is somewhat unpredictable.
#

#
# You may want to add system load-average to the outputs, if so,
# here is one way to do it fairly platform independently, usable
# in case you don't have SNMP agent available for it.
#

# open(f, "/usr/bin/uptime|") || crash("Cannot open uptime: $!");
# $U = <f>; chomp $U; @U = split(/ ,/,$U);
# close(f);
# $aver = $U[$#U-2];  # The three load-avgs are at offsets: -2, -1, -0
#                     # They are 1/5/15 minutes averages respectively
#		      # The value may trail with extra ",", but it should
#		      # not be much of a problem..

open(f, "/usr/bin/mailq -sQQ |") || crash("Cannot open mailq: $!");

($routerq) = split(' ', <f>);
($transpq) = split(' ', <f>);

while ($l = <f>) {
	chomp($l);
	$l =~ s/\s+/ /g;
	(@t) = split (' ', $l);
	if (@t[0] eq "Kids:") {
		($kids, $idle, $msgs, $threads, $rcpnts) = (@t[1], @t[3], @t[5], @t[7], @t[9]);
	} elsif (substr($l, 0, 1) ne ' ') {
		push @dst, @t[0];
	} elsif (@t[0] eq "Threads:") {
		push @dst, @t[1,3];
	}
}

close(f);

#
# Pick either, format changes...
#
  print       "$routerq $transpq $kids $idle $msgs $threads $rcpnts @dst\n";
# print "$aver $routerq $transpq $kids $idle $msgs $threads $rcpnts @dst\n";

exit 0;

sub crash {
	print "\nAiee: @_\n";
	exit 1;
}
