#! /s/std/bin/perl -w
use strict;


#my($Mailbox) = '/var/spool/mail/chaos';
my($Mailbox) = '/usr3/chaos/Mail/IN';
my($Scandir) = '/usr3/chaos/Mail';


#==============================================================================
# No user servicable parts below


main();


#==============================================================================
sub ScanMailbox($)
{
	my($Mailbox) = @_;

	if(!open(MAILBOX, $Mailbox))
	{
		print STDERR "Unable to open '$Mailbox' because of $!\n";
		return undef;
	}

	my($State) = 'scanning';

	my($From, $Subject, $Status, $Line);

	my(@Messages);

	while(defined ($Line = <MAILBOX>))
	{
		chomp($Line);
		if($State eq 'scanning')
		{
			if($Line =~ /^From .+/)
			{
				$State = 'inheader';
			}
		}
		elsif($State eq 'inheader')
		{
			if($Line =~ /^From: /)
			{
				($From) = ($Line =~ /^From: (.+)$/);
			}
			elsif($Line =~ /^Subject: /)
			{
				($Subject) = ($Line =~ /^Subject: (.+)$/);
			}
			elsif($Line =~ /^Status: /)
			{
				($Status) = ($Line =~ /^Status: (.+)$/);
			}
			elsif($Line =~ /^$/)
			{
				if(!(defined $Status))
				{
					push @Messages, [$Subject, $From];
				}

				$State = 'scanning';

				$Status = undef;
				$From = undef;
				$Subject = undef;
			}
		}
	}
	close(MAILBOX);

	return @Messages;
}


#==============================================================================
sub PrintMessageSummary
{
	my($Title, @Messages) = @_;

	if($#Messages > -1)
	{
		my($DividerLength) = 79 - length($Title);
		print $Title.'-'x$DividerLength."\n";
	}

	my($Subject, $From);
format STDOUT =
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<
$Subject,                                                        $From
.

	my($Message);
	my($Count) = 0;

	foreach $Message (@Messages)
	{
		($Subject, $From) = @{$Message};
		if(!defined $Subject) { $Subject = '<none>'; }
		if(!defined $From) { $From = '<none>'; }
		$Subject .= '.'x60;
		write;
		$Count++;
	}

	return $Count;
}

#==============================================================================
sub main()
{
	my($AnythingUp) = 0;

	my(@Messages) = ScanMailbox($Mailbox);

	$AnythingUp += PrintMessageSummary("IN", @Messages);


	opendir(DIR, $Scandir);
	my(@Files) = readdir(DIR);
	closedir(DIR);

	my($File);
	foreach $File (@Files)
	{
		if($File =~ /^IN\..+/o and -s "$Scandir/$File")
		{
			my(@Messages) = ScanMailbox("$Scandir/$File");
			$AnythingUp += PrintMessageSummary("$File", @Messages);
		}
	}


	if($AnythingUp == 0) { print "Nothings up.\n"; }
	else 
	{
		if(fork())
		{
		}
		else
		{
			exec("/usr3/chaos/bin/dingdingding");
		}
	}

	
	if(-s "/var/spool/mail/chaos")
	{
		print "PANIC!  There's stuff in your /var/spool/mail/chaos!\n";
	}
}


