#!/opt/bin/perl

# This was a quick hack.
# --josh

$maxsm=60; # Maximum # of sendmails to allow to run at any given time (via ps)

print "Enter subject: ";
chop($subject=<>);

print "Enter file to mail around: [none] ";
chop($file=<>);

if ($file =~ /^\s*$/) {
    print "Doing file edit now...";
    if ( ! $ENV{EDITOR}) { $ENV{EDITOR}=pico; }

    $file="$ENV{HOME}/mmdraft.$$";
    system ("$ENV{EDITOR} $file");

    print "Editing complete.\n";
} else {
    die "File $file not found." if ( ! -f $file); 
}

print "\nThe following will be sent:\n" . "-" x 60 . "\n";
system ("more $file");
print "-" x 60 . "\n";

print "Press enter to continue, ctrl-c to quit.\n"; $_=<>;

open (LOG,">/tmp/massmail.log") || die;
select(LOG); $|=1; select(STDOUT);
print LOG "LOG STARTED: " . `date`;

print "Logging to /tmp/massmail.log\n";

open (A,"/etc/aliases");
foreach (<A>) {
    ($from)=split (/:/);
    $skipuser{$from}=1;
}
close(A);

$namelist="/etc/passwd";
print "File with list of users or <enter> for ALL users: "; $_=<>;
chomp;
if ($_) { $namelist=$_; }

open (P,"$namelist");
foreach (<P>) {
    chomp;
    ($user)=split(/:/);
    if ($skipuser{$user}) {
	print "Skipping $user, since it is an alias\n";
    } else {
	push(@group,$user);
	$num++;
	if ($num >= 15) {
	    push (@mailing,join ',',@group);
	    undef @group;
	    $num=0;
	}	
    }
}
push (@mailing,join ',',@group);
close(P);

open(M,"$file") ; @msg=<M>; close (M);

$numgrps=scalar(@mailing);
print "Mail will be sent in $numgrps groups of 15 addresses\n";

$num=0; 
$mailto=shift @mailing;
while($mailto) {
    # Check to see how many sendmails are running. 
    chop($numsm=`ps -ef | grep sendmail | wc -l`);
    if ($numsm > $maxsm) {
	print "Throttling, $numsm (of a max of $maxsm allowed) are running\n";
	print "$num of $numgrps groups delivered so far\n";
	sleep(6);next;
    }
    $_=`uptime`;
    ($loadavg)=/average: ([^,]+),/;
    if ($loadavg > 8) {
	print "Throttling, load average too high\n";
        print "$num of $#mailing groups delivered so far\n";
        sleep(6);next;
    }

    chomp($date=`date`);
    print LOG "$date: sending to $mailto\n";
    open (S,"|/usr/lib/sendmail -t");
    print S "Subject: $subject\nBcc: $mailto\nPrecedence: bulk\n\n";
    foreach(@msg) {print S;}
    print S "\n.\n";
    close(S);
    $num++;
    print ".";
    sleep(2);
    $mailto=shift @mailing;
} 

print "done ($num groups of 15 delivered)\n";
    



