#!/usr/local/bin/perl

# This is a script that tells who is in a given room, based on a data
# file named <bldg>.who.data with the following format:
# <dept>	<room>	<URL>
# e.g. the file tb.who.data has the following line:
# ge		105	http://uxh.cso.uiuc.edu/~gedept/ge/directory/faculty/Goldberg.html
# (The department name is to update the information properly, Talbot, for example, has
# people from TAM and Aero both in it, and we want to be able to update the
# Aero people separately.)

# This script parses the query string and data file to figure out where the
# person's URL really is, then does a relocate to pass that info.


###############################################################################
# Set up knownledge about the world outside this script
###############################################################################
$DATADIR = "/www/navigation/data";



###############################################################################
# Parse the query string
###############################################################################
$query = $ENV{'QUERY_STRING'};

if ($query =~ /room=(\d*\w?)/) {
	$room = $1;
	}
else {
	print "Content-type: text/html\n\n";
	print "<h1>Error</h1>\n";
	print "Sorry, this script needs a room number and building to work!<p>\n";
	print "Usage:who_is_in?room=<i>room</i>&bldg=<i>bldg</i>.<p>";
	die;
	}

if ($query =~ /bldg=(\w*)/) {
	$bldg = $1;
	}
else {
	print "Content-type: text/html\n\n";
	print "<h1>Error</h1>\n";
	print "Sorry, this script needs a room number and building to work!<p>\n";
	print "Usage:who_is_in?room=<i>room</i>&bldg=<i>bldg</i>.<p>";
	die;
	}

# print "ROOM is $room<p>\n";
# print "BLDG is $bldg<p>\n";

###############################################################################
# Read and parse the data file
###############################################################################
if (!open(DATAFILE, "$DATADIR/$bldg.who_is_in.data") ) {
	print "Content-type: text/html\n\n";
	print "<h1>Error</h1>\n";
	print "Cannot read file $DATADIR/$bldg.who_is_in.data.<br>\n";
	die;
	}

while (<DATAFILE>) {
	if (/^([\w\-]*)\s*([\w]*)\s*([\w*:\/\.~\'\-]*)\s*(.*)/) {
		if ($room eq $2) {
			# print "URL is $3, room is $2\n";
			push(@munged, $3 . "@" . $4);
			break;
			}
		}
	}

if ($#munged == 0) {
	
	$mungee = pop(@munged);
	($url, $person) = split(/@/, $mungee,2);
	if ($url) {
		print "Location: $url\n\n"; 
		}
	}

elsif ($#munged > 0) {
	print "Content-type: text/html\n\n";
	print "<h1>Room $room</h1>\n";
	print "There is more than one entry for Room $room.  Your options are:\n";
	print "<ul>\n";
	while ($#munged >= 0) {
		$mungee = pop(@munged);
		($url, $person) = split(/@/, $mungee,2);
		print "<li><a href=$url>$person</a><br>\n";
		}
	print "</ul>\n";
	
	}
else {
	print "Content-type: text/html\n\n";
	print "<h1>Deserted</h1>\n";
	print "There is nobody listed as being in room $room, sorry.\n";
	}


