#!/usr/bin/perl

################################
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details, published at
# http://www.gnu.org/copyleft/gpl.html
#
#This program is written in Persistent Systems Pvt Ltd (http://www.persistent.co.in)
#Author : sopan_shewale@persistent.co.in
#Date   : 8/Feb/2005
#
#The basic idea is taken from SessionPlugins's logon script.
#The script is modifying ENV{REMOTE_USER} value  after authentication 
######################

sub BEGIN { $ENV{PTKDB_STOP_TAG_COLOR} = "yellow" } 
use CGI::Carp qw(fatalsToBrowser);
use CGI;
use Mail::IMAPClient;  ## Used only in case of IMAP server is used for authentication
                       ## Feel free to comment if you are not using IMAP. 

### IMAP server for using authentication
### Not bothered about different port, assuming server is running on defualt port
my $imapserver = 'imap.example.com';




BEGIN {
    # Set default current working directory (needed for mod_perl)
    if( $ENV{"SCRIPT_FILENAME"} && $ENV{"SCRIPT_FILENAME"} =~ /^(.+)\/[^\/]+$/ ) {
        chdir $1;
    }
    # Set library paths in @INC, at compile time
    unshift @INC, '.';
    require '../bin/setlib.cfg';
}
use TWiki;
use TWiki::Plugins::SessionPlugin;
$query = new CGI();


my $username = $query->param('username');
my $password = $query->param('password');

main();

sub main
{
    my $thePathInfo = $query->path_info(); 
    
  
    ##If you are using IMAP, uncomment following line, do_login routine should be called.  
    my $the_user = do_login($username, $password);
    ## End of IMAP seting


   if ($the_user eq '') { 
	   $ENV{REMOTE_USER} ="guest"; 
	   my $oopsurl = $query->param('url');
            $oopsurl =~ s/https/http/;   ## change https to http 
            $oopsurl =~ s/bin-ssl/bin/;   ## change https to http 
           my @oopsurlarray = split /logon/, $oopsurl;
	    $oopsurl = $oopsurlarray[0]."oops";
	      
	   $query->delete_all(); 
	   &TWiki::redirect($query, "$oopsurl?template=oopsauth");   }
   else { 
	   $ENV{REMOTE_USER} = $the_user; }  

    my $theRemoteUser = $query->remote_user();
    

    my $theTopic = $query->param( 'url' );
   
   # &TWiki::Func::writeDebug("........$theTopic"); 

    my @topiclisting = split/logon/, $theTopic;  ## The logon word is part of 
                                                 ## %SESSIONLOGONURL% variable
    foreach (@topiclisting) { $theTopic = $_;}
 
    $theTopic =~ s/\/+//;  ## Remove all "/" from begining of string. 
    my $theUrl = $query->url;
    $query->delete_all();    ###This was required... reset the $query 
 ( $topic, $web ) = 
	&TWiki::initialize( $thePathInfo, $theRemoteUser, $theTopic, $theUrl, $query );

    my $url = &TWiki::getViewUrl( $TWiki::webName, $topic );

    $url .= ( '?' . $query->query_string() ) if $query->query_string();
    $url =~ s/^https/http/;   ## change https to http 
    #$url =~ s/:8887//;   ## change https port number, required if you are running https on non-default port. 

    &TWiki::redirect( $query, $url );
}


## do_login authenticates users from authentication system.
## We are using IMAP server, so using IMAPClient to get authenticated. 
## Any other system can be used--best could be LDAP 
## You have to comment the following method if you are not using IMAP 
sub do_login {
  
       my $user     = shift;
       my $pass     = shift;
       my $user_name = '';
       if ($pass eq '') { return $user_name;}
       my $imaphost = $imapserver;
       eval {
       my $imap = Mail::IMAPClient->new(
                         Server=> $imaphost,
                         User => $user,
                         Password => $pass,
                         Clear => 5 );
        if($imap->Connected() && $imap->Authenticated()) { $user_name = $user; }
        $imap->close; 
        };
      return $user_name;
}



