#!/usr/local/apps/perl-5.8.8/bin/perl

=head1 NAME

login.cgi 

=head1 VERSION

This document refers to version 1.0 of login.cgi, released MMMM, DD, YYYY.

=head1 SYNOPSIS


=head1 DESCRIPTION

=head2 Overview

Overview of the purpose of the file.

=head2 Constructor and initialization.

if applicable, otherwise delete this and parent head2 line.

=head2 Class and object methods

if applicable, otherwise delete this and parent head2 line.

=cut

use strict;
use lib "../";
use Manatee;
use Manatee::GetManateeURLs;
use Manatee::GetManateeTemplate;
use Manatee::GetManateeParameters;
use Coati::Logger;
use Data::Dumper;
use CGI qw (:standard);
use CGI::Carp qw(fatalsToBrowser set_message);

### Add content to template and dump page 
my $logger;
BEGIN {
    $logger = new Coati::Logger('LOG_FILE'=>"/tmp/login.cgi.log",
				'MODE'=>"clobber",
				'LOG_LEVEL'=>&param('DEBUG')); 
    set_message(\&Manatee::GetManateeTemplate::get_error_handler);
}

my $mylogger = Coati::Logger::get_logger(__PACKAGE__);
my $Manatee = new Manatee();
my($DEFAULT_COOKIE_SETTING) = 1;

my($redir) = param('redir');

if($redir eq ""){
    $mylogger->debug("Checking query string $ENV{QUERY_STRING} for $redir URL") if $mylogger->is_debug;
    #check if $redir looks like a url
    if(($ENV{QUERY_STRING} =~ m|^/|) || ($ENV{QUERY_STRING} =~ m|http://|)){
	$redir = $ENV{QUERY_STRING};
	$redir =~ s/keywords=//;
	$mylogger->debug("Setting redir string to $redir. Parsed from $ENV{QUERY_STRING}") if $mylogger->is_debug;
    }
}
else{
    $mylogger->debug("Redirect url specified as $redir");
} 
#
# Write login to cookie and redirect
if(param('do_login') == 1) 
{
    	$mylogger->debug("Setting login") if $mylogger->is_debug;
    	my $parameters = new Manatee::GetManateeParameters();
    	my $cookie = $parameters->set('user'=>param('user'),
				  'password'=>param('password'));
    	$mylogger->debug("Writing cookie ",Dumper($cookie)) if $mylogger->is_debug;
    	print header(-cookie=>$cookie);
	if($redir ne "")
	{
		$mylogger->debug("Adding db=".param('db')." to redir URL $redir") if $mylogger->is_debug;
		if($redir =~ /db\=\w+/) 
		{
	    		my $newdb = param('db');
	    		$redir =~ s/db\=\w+/db\=$newdb/;
		}
		else 
		{
	    		$redir .= "?db=".param('db');
		}
    	}
	printRedirect($redir);
}
#
# Login required
elsif($redir){
    $mylogger->debug("Printing login with redirect url=$redir") if $mylogger->is_debug;
    printLogin($redir);
}
elsif(!param('db')) {
    $mylogger->debug("Database parameter missing. Printing login") if $mylogger->is_debug;
    printLogin();
}
#
# Check for cookie or params or login
else{
    &Manatee::GetManateeParameters::import_stored_parameters();
    if(param('user') ne "" && param('password') ne ""){
	$mylogger->debug("Username and password detected. Attempting redirect to $redir") if $mylogger->is_debug;
	printRedirect($redir);
    }
    else{
	$mylogger->debug("Username and password missing. Printing login") if $mylogger->is_debug;
	printLogin();
    }
}

sub printRedirect()
{
$mylogger->error("here 1");
    my($redir,$header) = @_;
    my $template = new Manatee::GetManateeTemplate('FILE'=>"redirect.tt",
						   'URL_HANDLER'=>new Manatee::GetManateeURLs(),
						   'NO_HEADER'=>$header
						   );
$mylogger->error("here 2");

    my $url = new Manatee::GetManateeURLs();
$mylogger->error("here 3");
    my $permit_denied = checkDatabasePermissions();
$mylogger->error("here 4");

    if($permit_denied) {
$mylogger->error("here 5");
	$redir = $url->getURL('login');
	$template->addText('ACCESS_DENIED'=>1,
			   'BAD_DB'=>param('db'),
			   'REDIR'=>$redir);
	$template->printPage();
    }
    else {
$mylogger->error("here 6");
	$redir = get_default_redir($url) if($redir eq "");
    	$mylogger->debug("Redirecting to $redir using redirect template") if $mylogger->is_debug;
	$template->addText('redir'=>$redir);
	$template->printPage();
    }
}

sub printLogin(){
    my($redir) = shift;
    my $template = new Manatee::GetManateeTemplate('FILE'=>"login.tt",
						   'URL_HANDLER'=>new Manatee::GetManateeURLs()
						   );
    $template->addText('page_title'=>"Manatee Login",
		       'page_header'=>"Manatee Login",
		       'NO_ORG'=>1,
		       'use_cookies'=>$DEFAULT_COOKIE_SETTING); 
    if($redir ne ""){
	$template->addText('redir'=>$redir);
	$mylogger->debug("Specifying redirect key as redir=$redir") if $mylogger->is_debug;
    }
    $mylogger->debug("Printing login page") if $mylogger->is_debug;
    $template->printPage();
}

sub get_default_redir(){
    my ($url) = @_;
    my $paramhash = {'db'=>param('db')};
    $redir = $url->getURL("gateway", {'db'=>param('db')});
    $mylogger->debug("Returning default redirect to gateway page") if $mylogger->is_debug;
    return $redir;
}

sub checkDatabasePermissions {
$mylogger->error("here in checkDatabasePermissions start");
    my $Manatee = new Manatee('user'=>param('user'),
			      'password'=>param('password'),
			      'db'=>param('db'));
$mylogger->error("here in checkDatabasePermissions after declaration");
    return $Manatee->db_to_permissions(param('db'));
}

exit 0;

__END__

=head1 ENVIRONMENT

List of environment variables and other O/S related information
on which this file relies.

=head1 DIAGNOSTICS

=over 4

=item "Error message that may appear."

Explanation of error message.

=item "Another message that may appear."

Explanation of another error message.

=back

=head1 BUGS

Description of known bugs (and any workarounds). Usually also includes an
invitation to send the author bug reports.

=head1 SEE ALSO

List of any files or other Perl modules needed by the file or class and a 
brief description why.

=head1 AUTHOR(S)

 The Institute for Genomic Research
 9712 Medical Center Drive
 Rockville, MD 20850

=head1 COPYRIGHT

Copyright (c) 2002, The Institute for Genomic Research. All Rights Reserved.






