#!/usr/bin/perl

use MIME::Parser;

my @SENDFAX_ARGS =
(
       "-n",
);

# These are for faxmiil compatibility
my %FAXMAIL_ARGS =
(
	'-s' 	=> 'shift @ARGV;',
	'-p' 	=> 'shift @ARGV;',
	'-W' 	=> 'shift @ARGV;',
	'-n'	=> '',
	'-d'	=> '',
);
while ($ARGV[0] =~ m/-/)
{
	if (defined $FAXMAIL_ARGS{$ARGV[0]})
	{
		eval "$FAXMAIL_ARGS{$ARGV[0]}";
	}
	shift @ARGV;
}

my $tmp = "/tmp/mail-$$";
mkdir $tmp, 0700;

my $number = $ARGV[0];
my $owner = $ARGV[1];

my $parser = new MIME::Parser;
$parser->output_under($tmp);

my $mail = $parser->parse(\*STDIN);

my  @parts;
my  @entities = ($mail);

while ($_ = shift( @entities))
{
    my  @p;
    if ( @p = $_->parts)
    {
        unshift @entities,  @p;
    } else
    {
        push  @parts, $_;
    }
}

my $from = $mail->head->get('From');
chomp $from;

if ($owner)
{
    push @SENDFAX_ARGS, "-o", $owner
}

system('/bin/echo', '/usr/bin/sendfax',
    @SENDFAX_ARGS,
       '-f', $from,
       '-d', $number,
       map ({$_->bodyhandle->path() }  @parts));

system("/bin/rm", "-rf", $tmp);
