#!/afs/athena/contrib/perl/perl
#
# $Id: net_lookup.pl,v 1.3 92/12/17 10:58:31 tompalka Exp $
#
# find things in the net-directory
#

$basefilename =     "/mit/net-directory/net-dir/net.directory.part";
$mail_to_colleges = "/mit/consult/doc/college-email-";

&parse_arguments();

print "please wait.  the search might take a while..\n\n";

&check_attaches();

# 
# call the file parser, passing the filename.  
#

! $mail_only && do {
    foreach $c ( 1..4 ) {
	$filename = $basefilename . $c;
	&parse_file($filename);
    }
};

! $netdir_only && do {
    foreach $c (1..3) {
	$filename = $mail_to_colleges . $c . ".bak";
	&parse_file($filename);
    }
};

#
# parse the command line arguments
#

sub parse_arguments
{
    for( $i=0 ; $i<@ARGV ; $i++ ) {
	if( $ARGV[$i] eq "-m" ) {
	    $mail_only = 1;
	    next;
	}
	if( $ARGV[$i] eq "-n" ) {
	    $netdir_only = 1;
	    next;
	}
	if( $ARGV[$i] =~ /-v/ ) {
	    $verbose = 1;
	    next;
	}
	if( $ARGV[$i] =~ /-/ ) {
	    &usage_and_die;
	}
	if( $ARGV[$i] != /^$/ ) {
	    $keyword = $ARGV[$i];
	} else {
	    &usage_and_die;
	}
    }		

    if( $keyword eq "" ) {
	&usage_and_die;
    }
}

#
# print the usage message and die
#

sub usage_and_die {
    die <<EOU;
	
 usage:
        net_lookup [-n] [-m] [-v] keyword
	    
 This program will search the Net Directory for all the entries that
 contain the specified keyword.

      -m --> search Mail To Other Colleges directory only
      -n --> search Network Directory only
      -v --> display name of file searched
 keyword --> keyword to search for

EOU
}    

#
# go through the file slurping paragraphs, and calling another
# procedure to check if the paragraph contains the keyword or not
#

sub parse_file {
    local($filename) = @_;

    if( $verbose == 1 ) {
	print "\n* searching through file $filename\n";
    }

    open(infile,$filename) || die "cannot open file $filename: $!\n";

    $entry = "";
    
    while(<infile>) {
	if( /^$/ ) {
	    &process_entry($entry);
	    $entry = "";
	    next;
	}
	$entry .= $_;
    }
    close infile;
}

#
# check whether the paragraph contains the keyword or not.
# if yes, then print it out
#

sub process_entry {
    local($entry) = @_;

    if( $entry =~ m/$keyword/i ) {
	print "\n",$entry;
    }
}
    

#
# attach appropriate filesystems if they ain't there
#

sub check_attaches {
    if( ! -d "/mit/consult" ) {
	system("attach -q consult");
    }

    if( ! -d "/mit/net-directory" ) {
	system("attach -q net-directory");
    }
}
