#!/usr/bin/perl

$MAIL = '/var/qmail/bin/qmail-inject';
use Getopt::Std;
getopts('f:m:s:b:B') or usage();
$opt_f or usage();

my $m_file = $opt_m;
my $message;
my $subj = $opt_s;
@ARGV or usage();
my $to = join ', ', @ARGV;
my $bcc = $opt_b || $ENV{FORGE_BCC} || $ENV{USER};
my $BCC = $opt_B ? "" : "Bcc: $bcc\n";

if ($m_file eq '-') {
  local $/;
  die "No subject specified; aborting" unless defined $opt_s;
  $message = <STDIN>;
} elsif ($m_file) {
  local $/;
  die "No subject specified; aborting" unless defined $opt_s;
  open M, "< $m_file" 
    or die "Couldn't open file $m_file for reading: $!; aborting";
  $message = <M>;
  close M;
} else {
  unless (-t STDIN) {
    die "standard input not a terminal; use -m and -s options; aborting";
  }
  unless (defined $opt_s) {
    print STDERR "Subject: ";
    chomp($subj = <STDIN>);
  }
  print STDERR "Enter message on standard input; use . to terminate.\n";
  while (<STDIN>) {
    last if $_ eq ".\n";
    $message .= $_;
  }
}
open M, "| $MAIL -f '$opt_f'" 
  or die "Couldn't run $MAIL: $!; aborting";

print M <<EOM;
From: $opt_f
Subject: $subj
To: $to
$BCC
$message
EOM

close M 
  or die "Couldn't exec $MAIL: $!; aborting";


exit 0;

# ----------------------------------------------------------------
sub usage {
  print <<EOM;
  $0 -f from [-s subject] [-m message file] [-b bcc] recipients...
    -f  specify 'from' address (mandatory)
    -s  specify subject (mandatory; will prompt in interactive mode)
    -b  Bcc recipient (default: \$USER ($ENV{USER}))
    -B    Suppress Bcc 
    -m  message body file ('-' means read stdin)
        If omitted, prompt for message (and subject if necessary)
        as per /bin/mail
EOM
  exit 1;
}
