#!/usr/bin/perl
#
#
#
use strict;
use Carp;
use Getopt::Std;
use Sys::Syslog;
use File::Temp;
no warnings 'utf8';

$main::VERSION = '2.10.0';

our(%opts);
getopts('vi:q:',\%opts);

if ($opts{V}) { print "$main::VERSION\n"; exit; }

my %conf;
$conf{inbox}     = $opts{i} || $conf{inbox}        || '/srv/benno/inbox';
$conf{queueid}   = $opts{q} || $$;
$conf{verbose}   = $opts{v};
$conf{version}   = $opts{V};

help_exit() if $opts{h};
if ($conf{version}) {
    print "Version $main::VERSION\n";
    exit;
}

openlog('benno-stdin2inbox','nowait,pid','mail');

## READ FROM STDIN AND EXIT ####################################################
my $msg = "Read file from STDIN\n";
print "$msg\n" if $conf{verbose};

eval {
    my $importfile = stdin2inbox(%conf);
    syslog('INFO',"Mail with queueid $conf{queueid} archived: $importfile.");
    print "Email archived: $importfile\n" if $conf{verbose};
};
if ($@) {
    my $err = $@;
    syslog('ERR',"ERROR: Mail with queueid $conf{queueid} cannot be saved in $conf{inbox}: $err");
    print STDERR "5.6.5 Cannot convert journal message.";
    exit 75;
} 
closelog;
exit;


### SUBS ###

### stdin2inbox
sub stdin2inbox
{
    my (%conf) = @_;

    my $inbox    = $conf{inbox};
    my ($content, $tmpfile, $infh, $outfh, $emlfile);
    my $filetpl = "$conf{queueid}_XXXXXXXXXX";

    $infh  = \*STDIN;
    while (my $line = <$infh>) {
        $content .= $line;
    }
    close $infh;

    my $outfh = new File::Temp($filetpl,
                               DIR => $inbox,
                               SUFFIX => '.tmp')
                    or die("Cannot open tempfile: $!\n");
    $tmpfile = $outfh->filename;

    print $outfh $content;
    if (! $outfh->close) {
        die("Cannot write tempfile $tmpfile: $!\n");
    }
    close $outfh;

    ($emlfile = $tmpfile) =~ s/(\.tmp$)/.eml/;
    link $tmpfile, $emlfile or die "Rename error: $! $tmpfile\n";
    unlink $tmpfile or die "Cannot unlink $tmpfile: $!\n";

    return $emlfile;
}


###
# read configuration from file
#
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;
      $config{$var} = $val;
  }
  close CONF;
  return %config;
}


### print help and exit
sub help_exit
{
    my $msg = shift;

    if ($msg) {
        print $msg,"\n\n";
    }

    print "Usage: $0 [-h] [<options>]\n";
    print "\n";
    print "Reads file from stdin and write atomic to inbox directory\n";
    print "     -i <inbox>      inboxdir (default /srv/benno/inbox)\n";
    print "     -q <queue_id>   queue id from mta (default: process id)\n";
    print "     -V              print version\n";
    print "     -v              verbose\n";
    print "     -h              print this help\n";
    print "\n";
    
    exit 1;
}


### EOP ###
1;


__END__

