#!/usr/local/bin/perl5

# maillog - print /var/log/maillog files in human readable format
#
#       erco@3dsite.com (Greg Ercolano)
#
#       This software is public domain. Please maintain version history.
#       Please notify me of bugs. Do not remove this header.
#       Use at your own risk.
#
#       VERS    DATE            AUTHOR          COMMENTS
#       1.00    10/25/98        Greg Ercolano   Initial version
#       x.xx    -		-		-
#

# main
{ 
    $maillog = "</var/log/maillog";
    $errflag = 0;

    foreach ( @ARGV )
    {
	if ( /-h/ || /^-$/ )
	{
	    print STDERR "usage: maillog [-errs] [log #]\n" .
	                 "examples: maillog         -- print entire log\n" .
			 "          maillog -errs   -- print only failed mail\n" .
			 "          maillog 1       -- maillog.1.gz\n";
	    exit(1);
	}
	elsif ( /-errs/ )
	    { $errflag = 1; }
	elsif ( /^[0-9]*$/ )
	    { $maillog = "gunzip -c /var/log/maillog.$_.gz|"; }
    }

    # header
    {
	my $dots="-"x80;
	printf("%-30s %-58s %s\n","From (CtlAddr)", "To (Relay)", "Status"); 
	printf("%.30s %.58s %.40s\n", $dots,$dots,$dots,$dots); 
    }

    unless ( open(FD, "$maillog" ) )
	{ print STDERR "$maillog: $!\n"; exit(1); }

    while ( <FD> )
    {
	if( /: from=/ ) 
	{
	    s/^.* from=/from=/;
	    @arr=split(/, /);
	    for($t=0; $t<=$#arr; $t++) 
	    {
	           if ( $arr[$t] =~ /from=(.*)/    ) { $info{from}=$1; $info{from} =~ s/[<>]//g; } 
		elsif ( $arr[$t] =~ /relay=(.*)/   ) { $info{relay}=$1; $info{relay} =~ s/\[.*\]//; $info{relay} =~ s/\s+//g; }
	    } 
	}

	if( /stat=/ ) 
	{
	    s/^.* to=/to=/;
	    @arr=split(/, /);
	    for($t=0; $t<=$#arr; $t++) 
	    {
		   if ( $arr[$t] =~ /to=(.*)/      ) { $info{to}=$1; $info{to} =~ s/[<>]//g; } 
		elsif ( $arr[$t] =~ /relay=(.*)/   ) { $info{relay}=$1; $info{relay} =~ s/\[.*\]//; $info{relay} =~ s/\s+//g; }
		elsif ( $arr[$t] =~ /ctladdr=(.*)/ ) { $info{ctladdr}=$1; $info{ctladdr} =~ s/\(.*\)//; } 
		elsif ( $arr[$t] =~ /stat=(.*)/    ) { $info{stat}=$1; } 
	    } 

	    if ( $errflag && $info{stat} =~ /^Sent/ ) { next; }

	    printf("%-30s %-58s %s\n",
		(($info{ctladdr}eq"-")?$info{from}:$info{ctladdr}),
		"$info{to} ($info{relay})",
		$info{stat});

	    undef %info;
	    $info{to}=$info{from}=$info{ctladdr}=$info{relay}=$info{stat}="-";
	}
    }
}
