#! /usr/bin/perl -w
use strict ;

my $assignName  = 'CHECK MOODLE FOR REAL SCORE' ;
my $nameFile    = '/home/brock/classes/434/f19/names.txt' ;
my $outputFile  = 'MailSend' ;
my @studLast    = ( ) ;
my @studEmail   = ( ) ;
my @studName    = ( ) ;


#Read student names
my ($nameFH, $line) ;
if (!open($nameFH, '<', $nameFile)) {
    print STDERR "Can't open ${nameFile}\n" ;
    exit 1 ;
}

while (defined($line=<$nameFH>)) {
    my ($lastName, $fullName, $email) ;
    chomp($line) ;
    if (($lastName, $fullName, $email) = ($line =~ /^([^=]+)=([^,]+),(.*)$/)) {
	push(@studLast,  $lastName) ;
	push(@studEmail, $email) ;
	push(@studName,  $fullName) ;
    } else {
	print STDERR "Bad line -- ${line}\n" ;
	exit 1 ;
    }
}

if ($#studLast != $#studEmail || $#studLast != $#studName) {
    print STDERR "Arrays ain't the same size\n" ;
}

my ($outFH) ;
if (!(open($outFH, '>', $outputFile))) {
    print STDERR "Unable to open ${outputFile}\n" ;
    exit 1; 
} else {
    print "Writing to  ${outputFile}\n" ;
    print $outFH "#! /bin/sh\n" ;
}

for (my $i=0; $i <= $#studLast; ++$i) {
    my $studentName  = $studName[$i] ;
    my $studentEmail = $studEmail[$i] ;
    my $studentLast  = $studLast[$i] ;
    my $studentFile  = "${studentLast}.pdf" ;
    my $command 
	= "/usr/bin/mutt -s \"${assignName} for ${studentName}\" -a " ;
    $command .= "\"${studentFile}\" " ;
    $command .= "-- ${studentEmail} < /dev/null\n" ;
    if (-e $studentFile) {
	print $outFH "echo \"mailing to ${studentEmail}\"\n" ;
	print $outFH $command ;
	print $outFH "sleep 20\n" ;
    } else {
	print $outFH "echo \"Nothing for ${studentLast}\"\n" ;
    }
}
close($outFH) ;
chmod(0755, $outputFile) ;
