#!/usr/local/bin/perl

print "Content-type: text/html", "\n\n"  ;

$now=time ;

require TimeUtilities ;
require ChatSign ;
$URLdir_executables=&ChatSign::URLdir_executables ;
$data_basedir=&ChatSign::data_basedir ;

$request_method=$ENV{'REQUEST_METHOD'} ;

if ($request_method eq "GET") {
$query_string=$ENV{'QUERY_STRING'}
} else {
$size_of_form=$ENV{'CONTENT_LENGTH'} ;
read(STDIN, $query_string, $size_of_form) ;
}

# Split the name-value pairs
@pairs = split(/&/, $query_string);

foreach $pair (@pairs) {
	($name, $value) = split(/=/, $pair);
	# Un-Webify plus signs and %-encoding
	$value =~ tr/+/ /;
	# Get rid of all non-alpha/numeric stuff esp " ' ,
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	# $value =~ s/['|"|`|,]//g;
	# Stop people from using subshells to execute commands
	# when using UCB mail (aka mailx).
	$value =~ s/~!/ ~!/g;
	$FORM{$name}=$value ;
}

$chatrequest="$data_basedir/$FORM{domain}/chats_requested.dat" ;
$chatrequestbak="$data_basedir/$FORM{domain}/chats_requested.dat.bak" ;
$chatrequest_update="$data_basedir/$FORM{domain}/chats_requested_update.dat" ;
    
open (CHATREQUEST,$chatrequest) ||  die "Cannot open $chatrequest\n" ;
open (TEMP,"> $chatrequest_update") || die "Cannot open $chatrequest_update\n" ;
while (<CHATREQUEST>) {
    chomp ;
    ($requestor,$now,$status)=split(/,/) ;
    if ($requestor eq $FORM{requestor}) {
	$status=chatting ;
    }
    print TEMP "$requestor,$now,$status\n" ;
}
close (CHATREQUEST);
close (TEMP);
rename ($chatrequest, $chatrequestbak) || die "Cannot rename $chatrequest to $chatrequestbak\n" ;
rename ($chatrequest_update, $chatrequest) || die "Cannot rename chatrequest_update to $chatrequest\n" ;

print <<ENUF;
<HTML>
<SCRIPT Language="JavaScript">
function stopclose ()
{
window.alert("Stop!") ;
return (false) ;
}
</SCRIPT>
<HEAD>
<TITLE>ChatSign for $FORM{domain}</TITLE>
</HEAD>
<FRAMESET rows="180,*">
        <FRAME SCROLLING=auto NAME="domainchatheader" SRC="$URLdir_executables/domain_chat_header.pl?requestor=$FORM{requestor}&domain=$FORM{domain}">
        <FRAME SCROLLING=auto NAME="domainchatfooter" SRC="$URLdir_executables/requestor_footer.pl?requestor=$FORM{requestor}&domain=$FORM{domain}">
</FRAMESET>
</HTML>
ENUF
