#-*- perl -*-
#
#  Copyright (C) 2001 Ken'ichi Fukamachi
#   All rights reserved. This program is free software; you can
#   redistribute it and/or modify it under the same terms as Perl itself. 
#
# $FML: Qmail.pm,v 1.1.1.1 2001/05/05 04:34:15 fukachan Exp $
#


package Mail::Bounce::Qmail;

use strict;
use vars qw(@ISA @EXPORT @EXPORT_OK $AUTOLOAD);
use Carp;

=head1 NAME

Mail::Bounce::Qmail - Qmail error message format parser

=head1 SYNOPSIS

=head1 DESCRIPTION

Parse bounce messages generated by qmail.

Qmail actually has a standard, called QSBMF (qmail-send bounce message
format), as describbed in

    http://cr.yp.to/proto/qsbmf.txt

=head1 METHODS

=head2 C<new()>

=cut

sub analyze
{
    my ($self, $msg, $result) = @_;
    my $state   = 0;
    my $pattern = 'Hi. This is the';
    my $end_pattern = '--- Undelivered message follows ---';

    # search data
    my ($addr, $reason);
    my $m = $msg->{ next };
    do {
	if (defined $m) {
	    my $num  = $m->num_paragraph;
	    for ( my $i = 0; $i < $num ; $i++ ) {
		my $data = $m->nth_paragraph( $i + 1 );

		if ($data =~ /$pattern/)     { $state = 1;}
		if ($data =~ /$end_pattern/) { $state = 0;}

		if ($state == 1) {
		    $data =~ s/\n/ /g;
		    if ($data =~ /\<(\S+\@\S+)\>:\s*(.*)/) {
			($addr, $reason) = ($1, $2);

			my $status = '5.x.y';
			if ($data =~ /\#(\d+\.\d+\.\d+)/) {
			    $status = $1;
			}
			elsif ($data =~ /\s+(\d{3})\s+/) {
			    my $code = $1;
			    $status  = '5.x.y' if $code =~ /^5/;
			    $status  = '4.x.y' if $code =~ /^4/;
			}


			$result->{ $addr }->{ 'Diagnostic-Code' } = $reason;
			$result->{ $addr }->{ 'Status' }          = $status;
		    }
		} 
	    }
	}

	$m = $m->{ next };
    } while (defined $m);

    $result;
}


=head1 AUTHOR

Ken'ichi Fukamachi

=head1 COPYRIGHT

Copyright (C) 2001 Ken'ichi Fukamachi

All rights reserved. This program is free software; you can
redistribute it and/or modify it under the same terms as Perl itself. 

=head1 HISTORY

Mail::Bounce::Qmail appeared in fml5 mailing list driver package.
See C<http://www.fml.org/> for more details.

=cut


1;
