#!/usr/bin/perl
#
# @(#)mailqto 1.2 91/11/25
#
#  Copyright (c) Steve Kinzler - October 1991.
#
#  Permission is given to distribute these sources, as long as the
#  copyright messages are not removed, and no monies are exchanged.
#
#  No responsibility is taken for any errors on inaccuracies inherent
#  either to the comments or the code of this program, but if reported
#  to me, then an attempt will be made to fix them.

# mailqto - summarize hosts for which there is deferred mail
# Steve Kinzler, kinzler@cs.indiana.edu, 5 Oct 1991

%cal = ('Jan',   0, 'Feb',  31, 'Mar',  59, 'Apr',  90, 'May', 120,
	'Jun', 151, 'Jul', 181, 'Aug', 212, 'Sep', 243, 'Oct', 273,
	'Nov', 304, 'Dec', 334);

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime time;
$now = $yday + ($hour * 60 + $min) / 1440;

chop ($localhost = `hostname`);
$localhost =~ s/\..*//;

open(MAILQ, "mailq; echo A |");
@items = split(/\nA/, join("", <MAILQ>));
shift @items; pop @items;

foreach (@items) {
	split(/\n/);
	next unless $_[1] =~ s/.*Deferred:?\s*(.*)\).*/\1/;
	$age = &age(split(/\s+/, $_[0]));
	for $i (2..$#_) {
		$host = &hostname($_[$i]);
		$count{$host}++;
		$ages{$host} = $age
		    if ! defined $ages{$host} || $ages{$host} < $age;
	}
	$reasons{$host} = $_[1];
}

foreach (sort by_age keys %count) {
	$out = sprintf("%2d %s %s %s\n", $count{$_}, &prage($ages{$_}),
					 $_, $reasons{$_});
	$out =~ s/^(.{0,79}).*/\1/;
	print $out;
}

sub by_age {
	($ages{$a} == $ages{$b}) ? $a gt $b : $ages{$a} < $ages{$b};
}

sub by_count {
	($count{$a} == $count{$b}) ? $a gt $b : $count{$a} < $count{$b};
}

sub age {
	if ($mon == 0 && $_[3] eq 'Dec') { $year--; }
	$day = $cal{$_[3]};
	if ($year % 4 == 0 && $_[3] ne 'Jan' && $_[3] ne 'Feb') { $day++; }
	$_[5] =~ /(.*):(.*)/;
	$then = $day + $_[4] - 1 + ($1 * 60 + $2) / 1440;

	$age = $now - $then;
	$age = (($year % 4 == 0) ? 366 : 365) - $then + $now if $age < 0;
	return $age;
}

sub prage {
	$days = int($_[0]);
	$hrs  = ($_[0] - $days) * 24;
	$mins = int(($hrs - int($hrs)) * 60);
	$hrs  = int($hrs);

	$hrs  = "0$hrs"  if  $hrs < 10;
	$mins = "0$mins" if $mins < 10;

	return "$days,$hrs:$mins";
}

sub hostname {
	local($_) = $_[0];

	s/^\s*//;
	s/.*<//;
	s/>.*$//;
	s/\s.*//;

	s/"(.*)::.*"/\1/;

	s/^@?$localhost[^:@%!]*://i ||
	s/@$localhost[^:@%!]*$//i   ||
	s/%$localhost[^:@%!]*$//i   ||
	s/^$localhost[^:@%!]*!//i;

	return 'local' unless /[:@%!]/;

	s/:.*//;
	s/.*@//;
	s/.*%//;
	s/!.*// && (/\./ || s/$/.uucp/);

	y/A-Z/a-z/;

	$_ = 'UNKNOWN' if /^$/ || /[^+-\.0-9_a-z]/;

	return $_;
}
