#!/usr/local/bin/perl

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

# Set up knowledge of data and executable dirs

use TimeUtilities ;
use ChatSign ;
$data_basedir=ChatSign::data_basedir ;
$URLdir_executables=ChatSign::URLdir_executables ;

$request_method=$ENV{'REQUEST_METHOD'} ;

if ($request_method eq "GET") {
$query_string=$ENV{'QUERY_STRING'} ;
exit (1) ;
} 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 ;

$websites="$data_basedir/websites.dat" ;

open (PASSWD,$websites) || die "Cannot open $websites file\n" ;
while (<PASSWD>) {
	chomp ;
	($domain,$password,$default_email_address,$operators)=split(/,/) ;
	if ($domain eq $FORM{domain}) {
		$matched=1 ;
		unless ($password eq $FORM{password}) {
			&wrong_username_or_password ;
		}
	}	
}

unless ($matched) { &wrong_username_or_password ; }

print <<ENUF;
<HTML>
<HEAD>
<TITLE>ChatSign - Chats Waiting for $FORM{domain} 
</TITLE>
</HEAD>
<FRAMESET rows="110,*">
        <FRAME SCROLLING=auto NAME="$FORM{domain}.header" SRC="$URLdir_executables/domain_greeting.pl?domain=$FORM{domain}">
        <FRAME SCROLLING=auto NAME="$FORM{domain}.footer" SRC="$URLdir_executables/domain_chats_waiting.pl?domain=$FORM{domain}">
</FRAMESET>
</HTML>
ENUF
exit (0) ;

sub wrong_username_or_password {
	print "Either the username [$FORM{domain}] or the password [$FORM{password}] you entered was incorrect.<BR>Please check both and change one before trying again." ;
	exit (0) ;
}
