#!/usr/bin/perl
#  Copyright 2001-2021 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.


my %lex = ('User Id' => 'User Id',
	   'Password' => 'Password',
	   'Duration' => 'Duration',
	   'Login' => 'Login',
	   'Log In' => 'Log In',
	   'Log Out' => 'Log Out',
	   'min' => 'min',
	   'No Userid Found' => 'No Userid Found',
	   'Incorrect Password' => 'Incorrect Password',
	   'Logged In' => 'Logged In',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'User' => 'User',
	   'Main' => 'Main',

	   );

my $self = 'tlogin.pl';
my $defaulttime = 90; # minutes; should be loaded from config


use DBI;
use CGI;
use CGI::Session;

my $q = CGI->new;
my %arr = $q->Vars;


eval require "../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

eval require "../lib/libsession.pl"; # contains login/ checkPassword/ checkCookieTime functions
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@<br>\n";
}


my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;

# foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }


if ( not $arr{page} or $arr{page} == -1 ) {
    print $q->header( -charset, $charset );
    printHTMLHeader();
    showStartPage();

} elsif ( $arr{page} == 1 ) { 
    delete $arr{page};
    doLogin();

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    doLogout();
} 



#----------------
sub showStartPage {
#----------------

    my $userid_env = $ENV{'REMOTE_USER'};

    print qq{<h2>$lex{User} $lex{'Log In'}</h2>\n};

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    if ( $arr{script} ) {
	print qq{<input type="hidden" name="script" value="$arr{script}">\n};
    }

    print qq{<table cellpadding="6" cellspacing="0" border="1">\n};

    print qq{<tr><td class="bra">$lex{'User Id'}</td>\n};
    print qq{<td><input type="text" name="userid" size="16" value="$userid_env"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Password}</td>\n};
    print qq{<td><input type="password" name="password" size="10"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Duration}</td>\n};
    print qq{<td><input type="text" name="duration" size="3" value="30"> $lex{min}</td></tr>\n};

    print qq{<tr><td class="cn" colspan="2">\n};
    print qq{<input type="submit" value="$lex{Login}"></td></tr>\n};

    print qq{</table></form></body></html>\n};

    exit;

}



#-----------
sub doLogout {
#-----------

    # $dbtype set in admin.conf
    my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
				undef,{Handle => $dbh}) or die CGI::Session->errstr;

    my $userid = $session->{userid};

    $session->param('logged_in', '0');
    $session->flush;

    print $q->header( -charset, $charset );
    printHTMLHeader();
    print qq{<h3>$lex{User}: $userid -  $lex{'Log Out'}</h1>\n};

    print qq{<p><form><input type="hidden" name="none">\n};
    print qq{<input type="button" value="Close" };
    print qq{onClick="parent.close()"></form></p>};

    print qq{</body></html>\n};

    exit;

}


#----------
sub doLogin {
#----------


    my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
				undef,{Handle => $dbh}) or die CGI::Session->errstr;

    # Set Session Values;
    # my $userid_env = $ENV{'REMOTE_USER'};
    my $userid = $arr{userid};

    # Check password/userid against database (-1 no user, -2 wrong password;
    my $error = checkPassword( $userid, $arr{password}, $dbh);

    if ($error == -1){
	print $q->header( -charset, $charset );
	print qq{<html><body><h3>$lex{'No Userid Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    if ($error == -2){ 
	print $q->header( -charset, $charset );
	print qq{<html><body><h3>$lex{'Incorrect Password'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $cookietime = checkCookieTime($arr{duration});

    # Set values for userid, logged_in and duration in session
    $session->param('logged_in','1');
    $session->expire('logged_in',$cookietime);
    $session->param('userid',$userid );
    $session->param('duration', $cookietime ); # was $arr{duration}
    # The duration value in the session has cookie markup: +20m format.

    # Now print page header...
    print $session->header( -charset, $charset );
    
    printHTMLHeader();
    print qq{<h3>$lex{User} $lex{'Log In'}</h3>\n};

    my $sth = $dbh->prepare("select firstname, lastname from staff 
     where userid = ?");
    $sth->execute($arr{userid});
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my ($firstname, $lastname) = $sth->fetchrow;

    
    print qq{$firstname $lastname<br>$lex{'Logged In'}<br>\n};

    if ( $arr{script} ) {
	print qq{<form action="$arr{script}" method="post" style="padding:1em;">\n};
	print qq{<input type="submit" value="$lex{Continue}">\n};
	print qq{</form>\n};

    } 

=head
else {
	# Print Close Form button
	print qq{<p><form><input type="hidden" name="none">\n};
	print qq{<input type="button" value="Close" };
	print qq{onClick="parent.close()"></form></p>};
    }
=cut

    print qq{</body></html>\n};

    exit; 

}


#------------------
sub printHTMLHeader {
#------------------

    # Print Page Heading
    print qq{$doctype\n<html><head><title>$title</title>\n};
    print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};
    print qq{[<a href="$tchpage">$lex{Main}</a> ]\n};

    if ( $arr{user} ) { # if user, jump to the password field.
	print qq{</head><body onload="document.forms[0].elements[2].focus()">\n};

    } else {
	print qq{</head><body onload="document.forms[0].elements[1].focus()">\n};
    }

    return;
}
