#-*- perl -*-
#
#  Copyright (C) 2001,2002,2003 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.9 2003/01/07 08:38:35 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

=cut


# Descriptions: parse qmail error message
#    Arguments: OBJ($self) OBJ($msg) HASH_REF($result)
# Side Effects: update $result
# Return Value: none
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);

			# XXX-TODO: we should use $self->address_clean_up() ?

			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;
			$result->{ $addr }->{ 'hints' }           = 'qmail';
		    }
		}
	    }
	}

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

    $result;
}


=head1 CODING STYLE

See C<http://www.fml.org/software/FNF/> on fml coding style guide.

=head1 AUTHOR

Ken'ichi Fukamachi

=head1 COPYRIGHT

Copyright (C) 2001,2002,2003 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 first appeared in fml8 mailing list driver package.
See C<http://www.fml.org/> for more details.

=cut


1;
