#!/usr/local/bin/perl -w

# mail-responder.pl
#   Responds with a preset response via SMTP
#     Designed to work in conjunction with the Majordomo or the Mailman wrapper
#     Will also work without a list manager when used with the -s option
#
#   Expected inputs:
#     incoming message on STDIN
#     -l <list name>
#     -s <email address> [optional]; alternate sender address for responses 
#     -r <path to response> [optional]; default= ~/lists/<list name>.response
#
#   06/28/2001 Version 1.1
#   Use and distribute this script as per the Artistic License
#   Igor S. Livshits <mailto:igorl@ayradyss.org>


# Define libraries and modules
#
push (@INC, 'pwd');		# add current directory to the search list
use Getopt::Long;		# command line options processor
use Net::SMTP;			# from libnet by Graham Barr


# Initialize
#
GetOptions("l|list=s" => \$listName,
	   "s|sender=s" => \$replySender,
	   "r|response=s" => \$responseFilePath
	   );

exit unless ($listName or ($replySender and $responseFilePath));
$responseFilePath= "$ENV{'HOME'}/lists/$listName.response"
  unless $responseFilePath;

# Parse the incoming message
#
while(<STDIN>)
{				# scan the incoming message
  $replyToAddress= $2 if /^(Reply-To:\s*)(.*)/;
  $fromAddress= $2 if /^(From:\s*)(.*)/;

  last if /^\n/;		# found the end of mail headers
}

$replyToAddress= $fromAddress unless $replyToAddress;
exit unless $replyToAddress;
#chop($replyToAddress) if $replyToAddress=~ /\n$/;

# Gather the response
#
open(Response, $responseFilePath)
  or die "Cannot read from <$responseFilePath>.";
while(<Response>)
{				# gather our response
  $mailMessage.= "To: $replyToAddress\n", next if /^To:/;
  $mailMessage.= $_;
}
close(Response);


# Mail the response
#
$mailer= new Net::SMTP();
$replySender= $listName."-admin\@".$mailer->domain()
  unless $replySender;

if ($mailer->mail($replySender)
    && $mailer->to($replyToAddress))
{
  $mailer->data();
  $mailer->datasend($mailMessage);
  $mailer->dataend;
}
$mailer->quit;


# We're done!
#
exit;