#!/usr/bin/perl -w

# fexmailforward is a filter for procmail and needed for the $fex_sender option,
# see fex.ph

# fexmailforward reads a mail from STDIN and forwards it to the real recipient
# with sendmail (or a CLI compatible like postfix).

$prg = $0;
$prg =~ s:.*/::;
$sendmail = '/usr/sbin/sendmail';

while (<STDIN>) {
  last if /^\s*$/;
  next if /^From ./;
  if (/^(Delivered-To|X-Original-To): fex\+(.+)_(.+)\@([\w.-]+)/) {
    $recipient ||= $2.'@'.$3;
    push @H,"X-Forwarded-By: fex\@$4\n";
  } else {
    push @H,$_;
  }
}

@B = <STDIN>;

if ($recipient and scalar(@H)>2) {
  open $sendmail,'|-',$sendmail,'-i',$recipient or die "$prg: $sendmail - $!\n";
  print {$sendmail} @H,"\n",@B;
  close $sendmail;
} else {
  die "$prg: unknown recipient\n";
}
