#!/usr/local/bin/perl

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

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

$now=time ;

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

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



print <<ENUF;
<HTML>
<META HTTP-EQUIV="Refresh" CONTENT="10; URL=$URLdir_executables/requestor_footer.pl?requestor=$FORM{requestor}&domain=$FORM{domain}"> 
<BODY>
<CENTER>
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=2>
ENUF

open (CONVERSATION,$chat_datafile) || warn "Cannot open $chat_datafile\n" ;
while (<CONVERSATION>) {
	chomp ;
	($who,$when,$what)=split(/\^/) ;
	# ($date,$time)=&TimeUtilities::make_unixtime_readable($when) ;

	if ($FORM{requestor} eq $who) { 
		$color="BGCOLOR=#eeeed4" ;
	} else { 
		$color="BGCOLOR=#eaeaea" ;
	} 

	$sorted_conversation{$when}="<TR $color><TD><font face=\"Arial, Helvetica, sans-serif\" size=\"2\"><B>$who</B></TD><TD><font face=\"Arial, Helvetica, sans-serif\" size=\"2\">$what</TD></TR>" ;
}
close (CONVERSATION) ;

foreach $time (sort backwards_by_number keys(%sorted_conversation)) {
	$counter++ ;
	if ($counter<11) {
		print "$sorted_conversation{$time}" ;
	}
}

print <<ENUF;
</TABLE>
</CENTER>
</BODY>
</HTML>
ENUF
exit (0) ;
sub by_number {
    if ($a < $b) {
        return -1;
    } elsif ($a == $b) {
        return 0;
    } elsif ($a > $b) {
        return 1;
    }
}

sub backwards_by_number {
    if ($a > $b) {
        return -1;
    } elsif ($a == $b) {
        return 0;
    } elsif ($a < $b) {
        return 1;
    }
}
