#!/usr/bin/perl
#
#  @(#)mailq.faces 1.3 91/05/06
#
#  Copyright (c) Steve Kinzler - April 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.

# Uncomment this line if you are running a version of faces earlier
# than version 1.5.0:
# $oldformat = 1;

$cols = 10;
$mqface = 'mailq';

# mailq.faces - faces script to monitor the mail queue
# Steve Kinzler, kinzler@cs.indiana.edu, 15 Jan 1991

$format = $oldformat ? "%-20s%-20s%-10s%-10s%-10s%-10s\n" :
		       "%s\t%s\t%s\t%s\t%s\t%s\n";

%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;

$n = 0;

open(MAILQ, "mailq; echo EOF |");

MAIN:
while (<MAILQ>) {
	$host = '';

	if (/no control file/) {
		$n++;
		$output .= sprintf($format, 'question', '', '<WAITING>', '',
							    '?,?,?', '');
	} elsif (/^A/) {
		split;
		$c = 0;
		while (<MAILQ>) {
			if (/^[ 	]/) {
				$c++ unless /^\s*\(/;
			} else {
				$user = $_[6];
				$user =~ s/^<//;
				$user =~ s/>$//;

				while ($user =~ /^@([^:]*):([^:].*)/) {
					$user = $2; $host = $1;
				}
				while ($user =~ /(.*)[%@](.*)/) {
					$user = $1; $host = $2;
				}
				while ($user =~ /([^!]*)!(.*)/) {
					$user = $2; $host = $1;
					$host .= '.uucp' unless $host =~ /\./;
				}
				while ($user =~ /([^:]*)::(.*)/) {
					$user = $2; $host = $1;
				}

				$user =~ s/^(.{0,20}).*/\1/ if $oldformat;
				$user =~ y/A-Z/a-z/ unless $user =~ /[a-z]/;
				$user =~ s/^postmaster$/postmaster/i;
				$wind = $user;
				$wind =~ s/^(.{0,10}).*/\1/ if $oldformat;

				if ($oldformat) {
					$host =~ s/^[^\.]*.//
						while length $host > 20;
				}
				$host =~ y/A-Z/a-z/;

				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;

				$w = $now - $then;
				$w = (($year % 4 == 0) ? 366 : 365)
				         - $then + $now if $w < 0;
				$w = int($w);

				$icon = "$w,$c,$_[1]";
				$icon =~ s/^(.{0,10}).*/\1/ if $oldformat;

				$n++;
				$output .= sprintf($format, $user, $host,
						   $wind, '', $icon, '');

				redo MAIN;
			}
		}
	}
}

close MAILQ;

printf $format, $mqface, '', 'MAILQ', $n, '', '';

printf("Cols=1 Rows=1\nNOMAIL\n"), exit if $n <= 0;

printf "Cols=%d Rows=%d\n", ($n > $cols) ? $cols : $n, ($n - 1) / $cols + 1;
print $output;
