#!/usr/local/bin/perl

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

$request_method=$ENV{'REQUEST_METHOD'} ;


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

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 ;
}

$now=time ;

$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 ;
	($who,$when,$status)=split(/,/) ;
	unless ($who eq $FORM{requestor}) {
		print TEMP "$who,$when,$status\n" ;
	} else {
		# print "Closing $email_address $now<BR>" ;
	}
}
close (CHATREQUEST);
close (TEMP);


        rename ($chatrequest, $chatrequestbak) || die "Cannot rename $chatrequest to $chatrequest.bak !" ;
        rename ($chatrequest_update, $chatrequest) || die "Cannot rename chatrequest_update!" ;


$now=time ;

$chat_datafile="$data_basedir/$FORM{domain}/chats/$FORM{requestor}" ;

open (ADDTOCONVERSATION,">> $chat_datafile") || die "Can't add to $chat_datafile" ;
print ADDTOCONVERSATION "$FORM{domain}^$now^$FORM{domain} closed chat with $FORM{requestor}\n" ;
close (ADDTOCONVERSATION) ;

print <<ENUF;
<HTML>
<HEAD>
<TITLE>ChatSign - Close Chat between $FORM{requestor} and $FORM{domain}</TITLE>
</HEAD>
<BODY BGCOLOR=lightblue>
<CENTER>
<H4>Chat between $FORM{requestor} and $FORM{domain}<BR>closed by $FORM{domain}</H4>

<FORM METHOD=POST ACTION="$URLdir_executables/domain_email_domain.pl">
<INPUT TYPE=hidden NAME=domain VALUE=$FORM{domain}>
<INPUT TYPE=hidden NAME=requestor VALUE=$FORM{requestor}>
<INPUT TYPE=Submit VALUE="Email Chat to $FORM{domain}">
</FORM>

</CENTER>
</BODY>
</HTML>
ENUF

exit (0) ;
