#!/usr/bin/env perl
############################################################
#
# $Id: send-mail,v 1.48 2013/10/03 17:24:24 jvanheld Exp $
#
############################################################

## use strict;

=pod

=head1 NAME

send-mail

=head1 VERSION

$program_version

=head1 DESCRIPTION

Send a mail with the parameters defined in I<RSAT_config.props> (I<smtp>,
I<smtp_sender>).

=head1 AUTHORS

Jacques.van-Helden\@univ-amu.fr, Bruno Contreras

=head1 CATEGORY

=over

=item util

=back

=head1 USAGE

send-mail -to recipient@mail.server [-subject 'email subject' [-i inputfile] [-v #] [...]

=head1 INPUT FORMAT

The input file must be a text file.

=head1 WISH LIST

=over

=item B<-a attachment>

Attach a file to the mail. This option can be called iteratively to attach
several files.

=back

=cut


BEGIN {
  if ($0 =~ /([^(\/)]+)$/) {
    push (@INC, "$`lib/");
  }
}
require "RSA.lib";
require RSAT::email;
use Email::Sender::Simple qw(sendmail);
use Email::Simple;
use Email::Simple::Creator;
use Email::Sender::Transport::SMTP;


################################################################
## Main package
package main;
{

  ################################################################
  ## Initialise parameters
  our $start_time = &RSAT::util::StartScript();
  our $program_version = do { my @r = (q$Revision: 1.48 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
  #    $program_version = "0.00";

  our %infile = ();
  our %outfile = ();
  our %args = (); ## Arguments passed to &RSAT::email::send_mail()
  our $STARTTLS = 0;
  our @starttlsparams = (); ## passed to &RSAT::email::send_mail_STARTTLS()
 
  our $verbose = 0;
  our $in = STDIN;
  our $out = STDOUT;

  ################################################################
  ## Read argument values
  &ReadArguments();

  ################################################################
  ## Check argument values

  ################################################################
  ## Open output stream
  $out = &OpenOutputFile($outfile{output});

  ################################################################
  ## Read input from either file or STDIN
  ($main::in) = &OpenInputFile($main::infile{input});
  while (<$main::in>) {
      $message .= $_;
  }
  close $main::in if ($main::infile{input});

  ################################################################
  ## Print verbose
  &Verbose() if ($main::verbose >= 1);

  ################################################################
  ## Execute the command
  if($STARTTLS == 1){
    &RSAT::email::send_mail_STARTTLS($message, $recipient, $subject, @starttlsparams);
  }
  else {
    &RSAT::email::send_mail($message, $recipient, $subject, %args);
  }

  ################################################################
  ## Report execution time and close output stream
  &close_and_quit();
}

################################################################
################### SUBROUTINE DEFINITION ######################
################################################################


################################################################
## Close output file and quit
sub close_and_quit {

  ## Report execution time
  my $exec_time = &RSAT::util::ReportExecutionTime($start_time); ## This has to be exectuted by all scripts
  print $main::out $exec_time if ($main::verbose >= 1); ## only report exec time if verbosity is specified

  ## Close output file
  if ($outfile{output}) {
    close $main::out;
    &RSAT::message::TimeWarn("Output file", $outfile{output}) if ($main::verbose >= 2);
  }

  ## CLOSE OTHER FILES HERE IF REQUIRED

  exit(0);
}


################################################################
## Display full help message 
sub PrintHelp {
  system "pod2text -c $0";
  exit()
}

################################################################
## Display short help message
sub PrintOptions {
  &PrintHelp();
}

################################################################
## Read arguments 
sub ReadArguments {
  my $arg;
  my @arguments = @ARGV; ## create a copy to shift, because we need ARGV to report command line in &Verbose()
  while (scalar(@arguments) >= 1) {
    $arg = shift (@arguments);


=pod

=head1 OPTIONS

=over 4

=item B<-v #>

Level of verbosity (detail in the warning messages during execution)

=cut
    if ($arg eq "-v") {
      if (&IsNatural($arguments[0])) {
	$main::verbose = shift(@arguments);
      } else {
	$main::verbose = 1;
      }


=pod

=item B<-h>

Display full help message

=cut
    } elsif ($arg eq "-h") {
      &PrintHelp();


=pod

=item B<-help>

Same as -h

=cut
    } elsif ($arg eq "-help") {
      &PrintOptions();


=pod

=item B<-i inputfile>

Text file containing the text of the message.

If no input file is specified, the standard input is used.  This
allows to use the command within a pipe.

=cut
    } elsif ($arg eq "-i") {
      $main::infile{input} = shift(@arguments);



=pod

=item	B<-to user@mail.server>

Email address of the recipient. 

Mandatory argument

=cut
    } elsif ($arg eq "-to") {
      $recipient = shift(@arguments);

=pod

=item   B<-subject 'email subject'>

Subject of the message.

=cut
    } elsif ($arg eq "-subject") {
      $subject = shift(@arguments);

=pod

=item	B<-starttls host::user::pass::sender@address>

Optional details for SMTP::STARTTLS servers, by default taken from ENV.

=cut
    } elsif ($arg eq "-starttls") {
      $STARTTLS = 1;
      my @params = split(/::/,$arguments[0]);
      if(scalar(@params) == 4) { # assumes host:user:pass::sender order
        @starttlsparams = @params;
        shift(@arguments);
      }

#     } elsif ($arg eq "-password") {
#     #       $args{sasl_password} = shift(@arguments);
#
# =pod
#
# # =item B<-password your_password_for_smtp>
#
# # Some SMTP servers require an authentification
#
# # =cut
#


    } else {
      &FatalError(join("\t", "Invalid option", $arg));

    }
  }

=pod

=back

=cut

}

################################################################
## Verbose message
sub Verbose {
  print $out "; send-mail STARTTLS=$STARTTLS";
  &PrintArguments($out);
  printf $out "; %-22s\t%s\n", "Program version", $program_version;
  if (%main::infile) {
    print $out "; Input files\n";
    while (my ($key,$value) = each %main::infile) {
      printf $out ";\t%-13s\t%s\n", $key, $value;
    }
  }
  if (%main::outfile) {
    print $out "; Output files\n";
    while (my ($key,$value) = each %main::outfile) {
      printf $out ";\t%-13s\t%s\n", $key, $value;
    }
  }
}


__END__
