#!/usr/bin/perl -w

=head1 NAME

mimeloop - parse a MIME stream, and print the parsed entity


=head1 SYNOPSIS

    mimeloop [-options] infile

Options for help:

    -help       Output help
    -man        Output manpage

Options to control parsing:

    -count COUNT             Number of iterations (default 10000)
    -extract-nested          Extract nested messages using NEST
    -extract-uuencode        Extract embedded uuencode
    -replace-nested          Extract nested messages using REPLACE

Options to control output:

    -dir DIR                 Output parts to disk under this directory
    -verbose                 Verbose output (debugging)


=head1 DESCRIPTION

Parse a MIME stream, and output the resulting entity.  This is
a nice way of eyeballing whether or not MIME-tools "understood"
your MIME message.

Due to nonuniqueness of MIME encodings, there is a very good chance
that your output will not I<exactly> resemble your input.


=head1 AUTHOR

Eryq, eryq@zeegee.com

=cut

use lib "lib";
use strict;
use Getopt::Long;
use Pod::Usage;
use MIME::Parser;
use MIME::Parser::Filer;
use MIME::Tools::PrefixingLogger;

#### Options:
my $Help;
my $Man;
my $Count = 10000;
my $DecodeHeaders;
my $Dir;
my $Verbose = 0;
my $Encoding;
my $ExtractNested;
my $ExtractUuencode;
my $ReplaceNested;

#------------------------------

sub main {

    ### Usage?
    pod2usage(1) if !@ARGV;
    GetOptions(
	       "help" => \$Help,
	       "man"  => \$Man,

	       "count=i"          => \$Count,
	       "decode-headers"   => \$DecodeHeaders,
	       "dir=s"            => \$Dir,
	       "encode=s"         => \$Encoding,
	       "extract-nested"   => \$ExtractNested,
	       "extract-uuencode" => \$ExtractUuencode,
	       "replace-nested"   => \$ReplaceNested,
	       "verbose"          => \$Verbose,
	       ) or pod2usage(2);
    pod2usage(1) if $Help;
    pod2usage(-verbose=>2, -exitstatus=>0) if $Man;

    ### Can do this?
    eval "require Devel::Leak;";
    $@ and die "you need Devel::Leak installed to run this script...\n $@\n";

    ### Args:
    MIME::Tools->debugging($Verbose) if $Verbose;

    ### Create context:
    my $handle;
    if (1) {
	
	### Set up parser:
	my $parser = new MIME::Parser;
	if ($Dir) {
	    $parser->output_to_core(0);
	    $parser->output_under($Dir);
	}
	else {
	    $parser->output_to_core('ALL');
	}
	$parser->extract_nested_messages($ExtractNested)
	    if defined($ExtractNested);
	$parser->extract_uuencode($ExtractUuencode);
	$parser->decode_headers($DecodeHeaders);
	$parser->ignore_errors(1);
		
	### Parse:
	for (my $i = 1; $i <= $Count; $i++) {
	    my $ent = $parser->parse_open($ARGV[0]);
	    $ent or die "MIME parsing failed!\n";
	    $parser->filer->purge;
	    print $i, "\n";	    

	    if ($i == 1) { Devel::Leak::NoteSV($handle); }	    
	}	
    };
    Devel::Leak::CheckSV($handle) if $Count > 1;    
}

$SIG{__WARN__} = sub { print STDERR "mimeloop: $_[0]" };
exit (&main ? 0 : 1);
1;

