#!/usr/local/bin/perl

# Adam J. Griff, Ph.D.
# GriffMonster, LLC 2001

# Goal:
# Send mail to people in a mailing list file and
# customize the letter for those people.

# Global:
# LISTFILE file for those receiving the mail

local($mailprog) = "/usr/bin/rmail";
local($mailing_list) = "./mailinglist";
local($mailfile) = "./message";

if ($#ARGV >= 2) {
  print "Usage: $0 [mailing list file] [mail file] \n";
  print "Defaults: $0 [$mailing_list] [$mailfile] \n";
  exit;
}

($mailing_list = $ARGV[0]) if (defined $ARGV[0]);
($mailfile = $ARGV[1]) if (defined $ARGV[1]);

print "Defaults: $0 [$mailing_list] [$mailfile] \n";

if (! (-f $mailfile)) {
  print "Could find mail file: $mailfile\n";
  exit;
}
$maildata = `cat $mailfile`;


if (! open(LISTFILE, "$mailing_list")) {
  print "Could not open mailing list file: $mailing_list\n";
  exit;
} else {
  local($recipient);
  local($ncount,$ecount)=(0,0);
  while($recipient=<LISTFILE>) {
    chop($recipient);
#   data file for deans office
#    local($email,$fullname,$ssn,$major,$GPA,$CREDITS,$IPCREDITS) = 
#	split(/!/,$recipient);
#    local($lastname, $rest) = split(/,/,$fullname);
#    local($firstname);
#    if ($rest =~ /(\w+)/) {
#      $firstname = $1;
#    } else {
#      $firstname = "yo";
#    }
#   data file from directory assistance
    local($lastname,$othername,$email) = split(/!/,$recipient);
    local($firstname) = split(/ /,$othername);
    local($fullname) = "$othername $lastname";

    $firstname = ucfirst(lc($firstname));
    $lastname = ucfirst(lc($lastname));
    local($login,$machine) = split(/@/,$email);
    if (! defined $machine || ! defined $login) {
      $ecount++;
      print "$ecount - No email address for - $fullname\n";
      next;
    }
#    if (($GPA < 3.0) || (($CREDITS-$IPCREDITS) < 60)) {
#    if ($GPA < 2.5) {
#      $ecount++;
#      print "$GPA - GPA is too low\n";
#      next;
#    }
#else {
#      $ncount++;
#      print"GOOD - $GPA ! $CREDITS ! $IPCREDITS\n";
#      next;
#    }

    $ncount++;
    eval $maildata;
    open (MAIL, "|$mailprog $email") || die "Can't open $mailprog!\n";
    print MAIL  "From: $from\n";
    print MAIL  "To: $email\n";
    print MAIL  "Reply-to: $from\n";
#    print MAIL  "Reply-to: $afrom{$major}\n";
    print MAIL  "Subject: $subject\n\n";
    print MAIL  "$text\n";
    close (MAIL);
    
    print "$ncount - Sent mail to $email - $fullname\n";


# Delays the interval between mailings
# So rmail doesn't have a fit
# It is not actual rmail having a fit but the computer since all the active
# rmails are running at once.
select(undef,undef,undef,1);
# select(undef,undef,undef,1);


  }
  close(LISTFILE);
  print "Mail sent to $ncount people.\n";
  print "Not Mailed to $ecount people.\n";
}
