#!/opt/contrib/bin/perl --
#
# lookfile.cgi - a script which displays lines from a specified file
#	which match the supplied search pattern
#	it should be placed in the same directory as the form calling it, with
#	"lookfile.cgi" called as the form handler
# See lookfile.html for a sample form that uses this script
#
# It expects the following fields to be present in the data from the client:
#    find	- the string (regular expression pattern) to look for
#
# It responds with any lines of information matching $find
#
# Originally written for use with cgiwrap by Lawrie Brown - Dec 95
#
### Customise the following information ###
$file = "YYY";		# name of file to search for info
$title = "Lookfile Response";	# title of response form

# need cgi-lib.pl for the following CGI utility routines:
#	&ReadParse, &PrintHeader
require "cgi-lib.pl";

# now read key=value pairs from form into hash table %in
&ReadParse(*in);

# deal with a dud form...
$error  = "";	# no errors yet, unless ...
$error .= "No find field returned from form.<br>\n" if (!defined($in{'find'}));

# grab the ones we need now and then delete them from the array %in
$find = $in{'find'};
delete($in{'find'});

# now do some sanity checks on the data
$error .= "No pattern to find! Please go back and enter a search pattern.<br>\n"
	unless $find =~ /\S+/;	# check search pattern is non-blank
$error .= "Unable to open ($file) to search for info!<br>\n" 
	unless -T "$file";	# check supplied file is a text file

# Print out a content-type for HTTP/1.0 compatibility
print &PrintHeader;
print "<html>\n";
print "<head>\n";
print "<title>$title</title>\n";
print "</head>\n";
print "<body>\n";
print "<h1>$title</h1>\n";

# now check for any errors and respond if any
if (length($error) > 0) {
   print "<h2>Ooops!</h2>\n";
   print "There is a problem with the information supplied:\n";
   print "<p>\n";
   print $error;
   print "<p>\n";
   print "Your input to the form has been discarded. Sorry about that.\n";
   print "You should go back and check that you have completed the form.\n";
   print "If the problem persists you may need to advise the form's author.\n";
   print "<p>\n";
} else {	# otherwise search for the wanted info
   print "<h2>Searching $file</h2>\n";
   print "<pre>\n";
   open(IN, "<$file");
   while ($line = <IN>) {
      print $line  if $line =~ /$find/i;	# case-insensitive search
   }
   close(IN);
   print "</pre>\n";
}
# send rest of HTML header in response
print "</body>\n";
print "</html>\n";
exit(0);

