#!/usr/local/bin/perl
#
# profs - add profs email addresses to accounts
#
# usage: profs config profs-in [files]
#             $CONFIG $PROFS   $STDIN

if ($#ARGV<2)
  {print STDERR "Usage: profs config profs-in [files]\n";exit 1;}
 
#
# find the numbers of the id and email fields
$inum = $enum = -1;
$config = shift;
open (CONFIG,$config) || die "$config: $!\n";
while (<CONFIG>)
{
	if (/:id:/) {($inum)=(split(':'))[0];}
	elsif (/:email:/) {($enum)=(split(':'))[0];}
}
close(CONFIG);

# slurp in email addresses keyed by SSN id
$profs=shift;
open (PROFS,$profs) || die "$profs: $!\n";
while (<PROFS>) {
	tr/A-Z/a-z/;
	/^(.........)(.*)@uicvmc.bitnet.*/;
	$email{$1} = "$2@uicvmc.aiss.uiuc.edu";
}
close(PROFS);

# Now read lines from input file matching where possible
while (<>) {
	chop;
	$line = $id = $_;
	$id =~ s/.*\t$inum://;
	$id =~ s/$inum://;
	$id =~ s/\t.*//;
	$e = $email{$id};
	if ($e ne "") {		# if there's a profs address for this id
		if ($line =~ /\t$enum:/) {	# entry already has email field
			if ($line =~ /\t$enum:[a-z0-9]+@uicvmc\.(bitnet|aiss.uiuc.edu)\t/i) {
				# but it was only a profs address so replace it
				$line =~ s/\t$enum:[^\t]*/\t$enum:$e/;
				print STDERR "$id\n";
			}
		}
		else {		# entry had no prior email entry
			$line =~ s/$/\t$enum:$e/;
			print STDERR "$id\n";
		}
	}
	print "$line\n";
}
