########################################################################################
#                                                                                      #
#   Author: Bertrand Neron,                                                            #
#   Organization:'Biological Software and Databases' Group, Institut Pasteur, Paris.   #  
#   Distributed under GPLv2 Licence. Please refer to the COPYING.LIB document.         #
#                                                                                      #
########################################################################################

import sys
import os.path

from Mobyle.MobyleError import *

import logging 
p_log = logging.getLogger('Mobyle.Policy')



def queue( queueName ):
    """
    @return: the name of the queue to be used to execute the job
    @rtype: string
    """
    return queueName


def emailCheck( **args ):
    """
    check if the email according to the local rules.
    @return:
     - Mobyle.Net.EmailAddress.VALID    if the email is valid
     - Mobyle.Net.EmailAddress.INVALID  if the email is rejected
     - Mobyle.Net.EmailAddress.CONTINUE to continue futher the email validation process
    """
    import Mobyle.Net

    user , domainName  = args['email'].split('@')
    if domainName == 'pasteur.fr':
        try:
            local = isLocal( args['email'] )
        except MobyleError , err:
            p_log.error( "an error is occured during checking local login : "+ str( err ))
            # I don't stop Mobyle for that. The user continue as an external user
            return Mobyle.Net.EmailAddress.CONTINUE
        
        if local:
            return Mobyle.Net.EmailAddress.VALID
        else:
            return Mobyle.Net.EmailAddress.INVALID
    else:
        return Mobyle.Net.EmailAddress.CONTINUE
        

def isLocal( email ):
    """
    @return: True if the userName is a pasteur login, False otherwise.
    @rtype: boolean
    """
    import ldap
    con = ldap.initialize( 'ldap://ldap.pasteur.fr' )
    try:
        con.simple_bind_s()
    except Exception , err :
        raise MobbyleError , err
    user , domainName  = email.split('@')
    
    base_dn='ou=personnes,dc=pasteur,dc=fr'
    if user.find('.') != -1:
        filter = '(& (objectclass=posixAccount) (mail=%s))' %email
    else:
        filter = '(& (objectclass=posixAccount) (uid=%s))' %user
    attrs =['mail']
    
    try:
        user = con.search_s( base_dn , ldap.SCOPE_SUBTREE , filter , attrs )  
    except Exception , err :
        raise MobyleError , err
    if user:
        try:
            ldapMail = user[0][1][ 'mail' ][0]
        except KeyError , err:
            #some one try to use a uid which have not mail attribute like dbmaint or sge
            p_log.critical( "some one try to connect with an uid which have not mail : " + str( email ) )
            return False
        return True
    else:
        return False
