#!/usr/bin/perl
#
#
#
use strict;
use MIME::Parser;
use MIME::Entity;
use Date::Format;

my ($arg_i,$arg_f,$mail_from,$send_to) = @ARGV;

my $DEBUG = $ENV{DEBUG};
my $config_file = $ENV{BENNOWEB_CONFIG} || '/etc/benno-web/benno.conf';

my %config = read_config($config_file);

my $sendmail_cmd    = $config{FORWARD_SENDMAIL} || '/usr/sbin/sendmail';
my $sender          = $config{FORWARD_SENDER}   || 'no-reply@benno-mailarchiv.de';
my $body_txt        = $config{FORWARD_BODYTXT}  || '/usr/share/benno-web/benno-mailarchiv-forward.txt';
my $body_html       = $config{FORWARD_BODYHTML} || '/usr/share/benno-web/benno-mailarchiv-forward.html';

my ($envelope_from) = $sender =~ /\<?(\S+\@\S+[^\>\s'"])/;

# read orignal mail from STDIN
my $parser = new MIME::Parser;
$parser->output_to_core(1);

my $forward_mail;
{
    local $/ = undef;
    $forward_mail = $parser->parse(\*STDIN);
}
my $forward_subject  = $forward_mail->head->get('Subject',0);
(my $forward_filename = $forward_subject) =~ s/[\s\*\\\/\&\,\[\]]/_/g;


my $top = MIME::Entity->build(
    From        => $sender,
    To          => $send_to,
    Subject     => $forward_subject,
    Type        => 'multipart/mixed',
    Encoding    => '-SUGGEST',
    'X-MAILER'  => 'Benno MailArchiv 2.10.7',
);
$top->head->delete('Content-Transfer-Encoding');

my $part_txt    = mime_part($body_txt,'text/plain') if (-r $body_txt);
my $part_html   = mime_part($body_html,'text/html') if (-r $body_html);
$part_txt || $part_html || die "Cannot read any part of forwarding mail body: $body_txt or $body_html\n";

my $body;
if ($part_txt && $part_html)    {
    $body = MIME::Entity->build(
        Type        => 'multipart/alternative',
        'X-MAILER'  => undef,
    );
    $body->head->delete('Content-Transfer-Encoding');
    $body->add_part($part_txt); 
    $body->add_part($part_html); 
}
elsif ($part_txt) {
    $body->add_part($part_txt); 
}
elsif ($part_html) {
    $body->add_part($part_html); 
}

$top->add_part($body);

$top->attach(
        Data        => $forward_mail->as_string,
        Encoding    => '7bit',
        Type        => 'message/rfc822',
        Disposition => 'attachment',
        Filename    => $forward_filename,
        'X-MAILER'  => undef,
    );


print "  Send mail with command: $sendmail_cmd -i -f $envelope_from $send_to\n" if $DEBUG;
open my $sendmail, "|$sendmail_cmd -i -f $envelope_from $send_to"
    or die "Cannot call $sendmail_cmd: $!";

print $sendmail $top->as_string;

close $sendmail;

### SUB ###
sub mime_part
{
    my ($filename,$type) = @_;

    local undef $/;
    open my $fh, $filename or die "Cannot open body part $filename: $!\n";
    my $content = <$fh>;
    close $fh;

    my $entity = MIME::Entity->build(
        Type        => $type,
        Charset     => 'UTF-8',
        Encoding    => 'quoted-printable',
        Data        => $content,
        'X-MAILER'  => undef,
    );

    return $entity;
}

sub read_config
{
  my $configfile = shift;
  my %config;
  # _very_ simple config file parser
  #
  # Config format:   var = val
  #
  open CONF, "$configfile" or die "Cannot open config file $configfile. $!\n";
  foreach my $line (<CONF>) {
      next if $line =~ /^$/;
      next if $line =~ /^#/;
      chomp $line;
      my ($var,$val) = split(/=/, $line,2);
      # strip ws
      $var =~ s/\s//g;
      $val =~ s/^\s+//g;
      $val =~ s/\s+$//g;
      print "  $var => $val\n" if $DEBUG;
      $config{$var} = $val;
  }
  close CONF;
  return %config;
}
