#!/usr/bin/perl

use MIME::Lite;
use Getopt::Std;

%type = ('gif' => 'image/gif',
         'jpg' => 'image/jpeg',
         'jpeg' => 'image/jpeg',
         'pdf'  => 'application/pdf',
         'html' => 'text/html',
         'htm' => 'text/html',
         'txt' => 'text/plain',
        );

$MAILER = "/var/qmail/bin/qmail-inject";

getopts('Qf:s:o:m:t:O') or usage();

if ($opt_Q) {
  $opt_O = 1;
  $opt_s ||= "attached file";
  $opt_m ||= "/dev/null";
}


$from = $opt_f || default_from();

sub default_from {
  my $user = $ENV{USER} || getpwuid($<);
  my $host = $ENV{HOSTNAME};
  $host ? join '@', $user, $host : $user;
}

if ($opt_o && $opt_O) {
  print STDERR "-O and -o are incompatible.\n";
  exit 1;
}
if ($opt_O) { $opt_o = "| $MAILER" }
unless (defined $opt_o) {
  if (defined $ENV{DRAFT}) {
    $opt_o = $ENV{DRAFT};
    $DRAFT = 1;
  } else {
    $opt_o = '-';
  }
}
if ($opt_o !~ /^[|>]/) {
  $opt_o = "> $opt_o";
}
open OUTPUT, "$opt_o"
  or die "Couldn't open output file $opt_o: $!; aborting";

if ($opt_m) {
  open MSG, $opt_m
    or die "Couldn't open message file $opt_m: $!; aborting";
  @MSG = <MSG>;
  close MSG;
} else {
  print STDERR "Enter message on standard input; use . to terminate.\n";
  while (<STDIN>) {
    last if $_ eq ".\n";
    push @MSG, $_;
  }
}
my $msg = MIME::Lite->new(From    => $from,
                          To      => $opt_t,
                          Subject => $opt_s,
                          Type    => 'TEXT',
                          Data    => \@MSG);  


for (@ARGV) {
  my ($suf) = (/\.([^.]*)$/);
  my $type = $type{lc $suf} || 'application/octet-stream';
  $msg->attach(Type     => $type,
               Path     => $_);

}

$msg->print(\*OUTPUT);

exit 0;

# ----------------------------------------------------------------
sub usage {
  my $df = default_from();
  print <<EOM;
  $0 -O [-f from] [-s subject] [-o outputfile] 
        [-m message body] [-t to] [attachments...]
    -o  deliver message to specified output file (-o"| command" OK)
        (default STDOUT)
    -O	inject message into mail system directly
    -f  specify 'from' address (default $df)
    -t  specify 'to' address (default none)
    -s  specify subject (default none)
    -m  specify input file for message body (-m"command |" OK)
        (default: read from stdin like /bin/mail)
EOM
  exit 1;
}
