#!/usr/bin/perl

use strict;
use Getopt::Std;
use Net::SMTP;
use POSIX qw(strftime);

#
# Check options and arguments
#

my %opts;
if (!getopts('hs:', \%opts) || $opts{h} || @ARGV == 0) {
    die "Usage: $0 -s subject to-addr\n";
}

my @recipients = @ARGV;


#
# Send mail
#
sub send_mail {
    my $subject = shift;
    my $message = shift;
    my @recipients = @_;

    # Recipients: add @iram.fr if needed and remove duplicates
    @recipients = map { s/^([^\@]+)$/$1\@iram.fr/; $_ } @recipients;
    my %uniq = map { $_ => 1 } @recipients;
    @recipients = keys %uniq;

    # Date: RFC 822 format
    my $date = strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time()));

    # Sender/From: use getpwuid because getlogin() don't work inside newgrp call
    (my $user_name) = getpwuid( $<);
    $user_name = $user_name.'@iram.fr';

    my $smtp = Net::SMTP->new("smtp.iram.fr");
    $smtp->mail( $user_name);
    $smtp->to( @recipients);
    $smtp->data( );
    $smtp->datasend( "From: $user_name\n");
    $smtp->datasend( "To: ".join( ", ", @recipients)."\n");
    $smtp->datasend( "Reply-To: noreply\n");
    $smtp->datasend( "Date: $date\n");
    $smtp->datasend( "Subject: $subject\n");
    $smtp->datasend( "\n"); # RFC 5322 requires an empty line between the header and the body
    $smtp->datasend( $message);
    $smtp->dataend( );
    $smtp->quit;
}

#
# read message from standard input
#

my $message;
while (<STDIN>) {
    $message .= $_;
}

#
# send mail
#

my $subject = $opts{s} ? $opts{s} : "no subject";
send_mail( $subject, $message, @recipients);

