#!/opt/local/bin/perl -w

# login.cgi

use strict;
use HTML::Entities ();
use CGI;
use lib '/Library/WebServer/perl/lib';
use EduFileTwo;

my $query = new CGI;

#my $ok_chars = 'a-zA-Z0-9 ,-';
my $ok_chars = '%+\-0-9<=>A-Z_a-z{|}@.,';
foreach my $param_name ( $query->param ) {
    $_ = HTML::Entities::decode( $query->param($param_name) );
    $_ =~ s/[^$ok_chars]//go;
    $query->param($param_name,$_);
}


#Declare some local variables to save typing.

my $user_id = $query->param('user_id');
# glp: remove " " and "-"
$user_id =~ s/-//g;
$user_id =~ s/ //g;   

my $course_id = $query->param('course_id');
my $password = $query->param('password');
#EduFileTwo::Util::printMessage( "Before password = $password" );
$password =~ tr/"%+\-0-9<=>A-Z_a-z{|}//cd;
#EduFileTwo::Util::printMessage( "After password = $password" );


#Error Checking Statements
if ($user_id eq ""){

	print $query->header;
	EduFileTwo::Util::printHead("");
	&printMessage("Invalid Field", "The User ID field was left blank. Please click back on your browser to try again.\n");
	EduFileTwo::Util::printFoot();
}
if ($password eq ""){

	print $query->header;
	EduFileTwo::Util::printHead("");
	&printMessage("Invalid Field", "The Password field was left blank. Please click back on your browser to try again.\n");
	EduFileTwo::Util::printFoot();
}

EduFileTwo::Util::printMessage( "Going to get student ID" );
my $student_id = EduFileTwo::Util::obtainStudentID($user_id);

if(!EduFileTwo::Util::isValidUser($user_id, $password, $course_id, $student_id))
{

	print $query->header;
	EduFileTwo::Util::printHead("");
	&printMessage("Invalid User", "Please click back on your browser to try again. It is possible that your account has not been enabled yet. Please contact your professor, if you believe this is the case.\n");
	EduFileTwo::Util::printFoot();
}

my $identifier = EduFileTwo::Util::initializeSession($student_id, $course_id);

my $cookie = $query->cookie(-name=>'login_id',
                             -value=>"$identifier");
#                             -expires=>'+1h',
#                             -path=>'/edufile/login.cgi',
#                             -domain=>'.uccs.edu',
#                             -secure=>0);

#my $cookie = $query->cookie( -NAME => "login_id", -VALUE => $identifier);


print $query->redirect(-url => "showfiles.cgi?course_id=$course_id", -cookie => $cookie );

exit(0);

#Subroutines
sub printMessage{
	print "<h1>$_[0]</H1>";
	print "<p>$_[1]</p>";
}
