#!/usr/athena/bin/perl

$query=$ENV{'QUERY_STRING'};
print("Content-Type: text/html\n\n");
$query =join(' ', @ARGV) if $ARGV[0];
print("\n");
if($ENV{'REQUEST_METHOD'} eq "GET"){
	&dolist if $ENV{'PATH_INFO'} eq "/list";
	$query =~ y/A-Z/a-z/;
	if($query eq ""){
	    &printform;
exit;
	}
	$fchar = substr($query, 0,1);
	undef $/;
	if(open(WF, "/var/www/data/gloss/$fchar/$query")){
	$out = (<WF>);	
	close(WF);	
	}
	else{$status =1;}
	print("<h1>MIT-WWW Glossary</h1><hr>\n");
	print $out unless $status;
	print "The word <tt>\"$query\"</tt> was not found in our glossary\n" if $status;
	print("</ul><hr>Bugs to <em>webmaster\@mit.edu</em>\n");
}
elsif($ENV{'REQUEST_METHOD'} eq "POST"){
	require 'parseform.pl';
	read(STDIN, $postdata, $ENV{'CONTENT_LENGTH'});
	%glosspost = &parseform($postdata);
	($lword = $glosspost{'word'}) =~ y/A-Z/a-z/;
	$lword =~ s#/##g;
	$lword =~ s#^\.+##;

	$fchar = substr($lword,0,1);
	if(! -d "/var/www/data/gloss/$fchar"){
		mkdir("/var/www/data/gloss/$fchar", 0777) || print $!;
	}
	$newword = 1 if (! -e "/var/www/data/gloss/$fchar/$lword");
	open(OUT, ">>/var/www/data/gloss/$fchar/$lword");
	print OUT "<h2>$glosspost{'word'}</h2><ul>" if $newword;
	print OUT "<li>",$glosspost{'def'};
	close(OUT);

	print("<h1>$glosspost{'word'}</h1><ul><li>$glosspost{'def'}</ul>\n");
	&printform;
}
else{
	print("Can't deal with method $ENV{'REQUEST_METHOD'}\n");
}

sub dolist {
    for $l ('a'..'z', 1..9){
	if(-e "/var/www/data/gloss/$l"){
	    print("<h1>$l</h1><ul>\n");
	    opendir(DIR, "/var/www/data/gloss/$l") || print $!;
	    while($file = readdir(DIR)){
		($fileesc=$file) =~ y/ /+/;
		print("<li><a href=\"../word?$fileesc\">$file</a>\n") 
		    if substr($file,0,1) =~ /\w/;
	    }
	    print("</ul>\n");
	}
    }
    exit;
}

sub printform {

	print <<EOForm;
<h1>Look up a word...</h1>
<form action="/cgi/word" method="GET">
Word: <input name="isindex">
</form>
<hr>
Here is the <a href="word/list">complete glossary index</a>
<hr>
<h1>Add a new word to the Glossary</h1>
<form action="/cgi/word" method="POST">
Word: <input name="word"><p>
<textarea name="def" cols=60 rows=15></textarea><p>
<input type="submit" value="Add definition"><p>
<input type="reset" value="Clear form">
</form>
EOForm

}
