#!/s/perl/bin/perl

###
### Add/check departmental phone numbers
###

require 5.000;

$Usage = "Usage: $0 db_name\n";
die ($Usage) unless $#ARGV == 0;	# Check argument count
$dbName = $ARGV[0];

$DIR = '/p/stat/Data/admin/';	# Set the directory
$FSEP = "\t";			# separate fields by tabs

open(PHONES, "< office_phones") ||
    die "Unable to open file office_phones: $!\n";
while (<PHONES>) {
    chop;
    ($office, $phone) = split(/$FSEP/, $_);
    $phones{$office} = $phone;
}
close(PHONES);

$DB = $DIR . $dbName;		# Name of database
$FORM = $DB . ".form";		# Name of emacs-lisp form definition
				# for database
open(FORM, "< $FORM") ||
    die ("Unable to open form file $FORM: $!\n");
undef $/; $form = <FORM>; $/ = "\n"; # slurp entire form file into a
				     # string
die "$FORM does not define the fields!\n"
    unless ($form =~ /\(forms-enumerate[^']*'\(([^\)]*)/);
@FIELDS = grep(!/^$/, split(/\s+/, $1));

rename($dbName, $dbName . ".bak") || # create a backup of the file
    die ("Unable to move $dbName to ${dbName}.bak: $!\n");
open(INPUT, "< $dbName.bak") ||
    die ("Unable to open $dbName.bak for input: $!\n");
open(OUTPUT, "> $dbName") ||
    die("Unable to open $dbName for output: $!\n");

$flen = $#FIELDS;

while (<INPUT>) {
    chop;
    $rcount++;			# keep track of the record count
    @thisRec = split(/$FSEP/, $_);
    die "Record $rcount has $#thisRec fields.  It should have $flen.\n"
	unless $flen == $#thisRec;
    $thishash = {};
    for (@FIELDS) {
	$thishash->{$_} = shift(@thisRec);
    }
    if (($office = $thishash->{'office'}) !~ /^\s*$/)  {
	if ($office !~ /^4[23][0-9][0-9]$/) { # does office number look ok?
	    warn "Unusual office number $office.\n";
	} elsif (!($phone = $phones{$office})) { # does office have a phone?
	    warn "No phone listing for office number $office. \n";
	} elsif ($phone !~ /\s/) { # Not multiple phones?
	    if (($myphone = $thishash->{'phone'}) =~ /^\s*$/) {
		$thishash->{'phone'} = $phone;
	    } elsif ($phone ne $myphone) {
		warn "Phone for office $office is given as $myphone in" .
		    "database $ARGV[0], record $rcount\n but $phone in" .
			"the office_phones database. \n";
	    }
	}
    }
    undef @rec;
    foreach $f (@FIELDS) {
	push (@rec, $thishash->{$f});
    }
    print OUTPUT join("$FSEP", @rec), "\n";
}

