#!/usr/athena/bin/perl

# This program reads a file of machine names and email addresses and sends
# a message to each

&initialize;
&process_args;
&send_mail;

#
# process_args - Process command line arguments
#
# Global variables set
#	$subject	Subject line for email messages
#	$from_person	Username to put in the From: field
#	$datafile	Location of file with contact information
#
sub process_args
{

    while (@ARGV) {
      ARGS: {
	  $_ = shift (@ARGV);
	  if ( /-sub/ ) {
	      $subject = shift (@ARGV);
	      last ARGS;
	  }
	  if ( /-f/ ) {
	      $from_person = shift (@ARGV);
	      last ARGS;
	  }
	  if ( /-da/ ) {
	      $datafile = shift (@ARGV);
	      last ARGS;
	  }
	  if ( /-m/ ) {
	      $messagefile = shift (@ARGV);
	      last ARGS;
	  }
	  print "Unknown option $_\n";
	  print "Usage is: $0 [-data <datafile>] ";
	  print "[-subject <subject line>]\n";
	  print "[-from <From field person>]";
	  print "-message <File with message text>\n";
	  exit 0;
      }
    }
    if (! defined ($subject)) {
	$subject = $default_subject;
    }
    if (! defined ($from_person)) {
	$from_person = $default_from;
    }
    if (! defined ($datafile)) {
	$datafile = $default_datafile;
    }
    if (! defined ($messagefile)) {
	print "You must specify a file containing the text of your message\n";
	exit 0;
    }
}

#
# Initialize - Set up defaults for parameters
#
# Global Variables Set
#	$default_subject
#	$default_from
#	$default_datafile
#
sub initialize
{
    $default_subject = "Test Machine(s) for Athena Release 8.0";
    $default_from = "$ENV{'USER'}";
    if ($default_from = "") {
	$default_from = "dot";
    }
    $default_datafile = "contacts.all";
}

#
# send_mail - Actually send the email
#
# Global Variables Referenced:
#	$datafile
#	$from_person
#	$subject
#
sub send_mail
{
    open (DATAFILE, $datafile) || die "Can't read input file $! \n";
    while (<DATAFILE>) {
	if ( /^[a-zA-Z1-9]/ ) {
	    ($machine, $contact) = split (" ", $_);

	    $machine =~ tr/A-Z/a-z/;
	    $machine =~ s/.mit.edu//;

	    $machines{$contact} .= $machine . "\n";
	}
    }

    open (MSG, "$messagefile") || 
	die "I cannot find the file with the message.\n";
    seek (MSG, 0, 0);
    foreach $contact (keys %machines) {
	chop ($machines{$contact});

		open (MAIL, "| /usr/lib/sendmail -oi -t") || 
	    die "Fork failed: $!\n";
	print MAIL <<EOMSG;
To: $contact
From: $from_person
Subject: $subject

EOMSG
    while (<MSG>) {
	s/_DATA_/$machines{$contact}/;
	print MAIL;
    }
    seek (MSG, 0, 0);
    close (MAIL) || die "pipe exited $?";
	system ("sleep 5");
    }
    close MSG;
}
