# -*- coding:utf-8 -*-
from os.path import join, isfile
#from creole.client import CreoleClient

from configobj import ConfigObj

conffile = "/etc/eole/ldapconf.conf"
dico = ConfigObj(conffile)

#dico = CreoleClient().get_creole()

LDAP_MODE = dico.get('ldap_mode', 'openldap') #FIXME
FORCED_PASSWORD_MODIFICATION_ALLOWED = True if dico['forced_password_modification_allowed'] == 'oui' else False
CHECK_FOR_USERNAME = dico['check_for_username']
EAD_IMPORT_WRITE_OPTIONS = dico['ead_import_write_options']
EAD_IMPORT_WRITE_PRIVE = dico['ead_import_write_prive']
USER_ATTRIBUTE = dico.get('user_attribute', 'uid')
# chemin des conteneurs
CONTAINER_PATH_FICHIER = dico['container_path_fichier']
CONTAINER_PATH_DOMAINE = dico['container_path_domaine']
CONTAINER_PATH_MAIL = dico['container_path_mail']
if CONTAINER_PATH_FICHIER == '':
    CONTAINER_PATH_FICHIER = '/'
if CONTAINER_PATH_DOMAINE == '':
    CONTAINER_PATH_DOMAINE = '/'
if CONTAINER_PATH_MAIL == '':
    CONTAINER_PATH_MAIL = '/'

# configuration LDAP
LDAPCONF = '/etc/eole/eoleldap.conf'
READERCONF = '/root/.reader'
if LDAP_MODE == 'ad':
    if isfile('/etc/eole/private/eole-seth-education.password'):
        with open('/etc/eole/private/eole-seth-education.password', 'r') as pw_fd:
            ldap_passwd = pw_fd.read().strip()
    elif isfile(join(CONTAINER_PATH_DOMAINE, 'etc/eole/private/eole-seth-education.password')):
        with open(join(CONTAINER_PATH_DOMAINE, 'etc/eole/private/eole-seth-education.password'), 'r') as pw_fd:
            ldap_passwd = pw_fd.read().strip()
    else:
        raise Exception('File etc/eole/private/eole-seth-education.password Not Found')
    ldap_server = dico.get('adresse_ip_ldap', '127.0.0.1')
elif isfile(LDAPCONF):
    exec(open(LDAPCONF).read())
else:
    raise Exception("Fichier %s non trouvé" % LDAPCONF)
if isfile(READERCONF):
    READER_PWD = open(READERCONF).read().rstrip()
else:
    READER_PWD = 'FIXME'

# initialisation de variables
num_etab = str(dico['numero_etab'])
acad = str(dico['nom_academie'])
domaine_mess = str(dico['domaine_messagerie_etab'])
if 'quota_hard_limit_percent' in dico:
    QUOTA_HARD_LIMIT_PERCENT = int(dico['quota_hard_limit_percent'])
SMB_SERVEUR = str(dico["smb_netbios_name"])
HOME_PATH = str(dico['home_path'])
AD_HOME_PATH = str(dico.get('adhome_path', '/home/adhomes'))
GROUP_PATH = join(HOME_PATH, 'workgroups')
CLASS_PATH = join(HOME_PATH, 'classes')
RECYCLAGE_PATH = join(HOME_PATH, 'recyclage')
OPT_PATH = join(HOME_PATH, 'options')
MAILDIR_PATH = join(HOME_PATH, 'mail')
GROUPWARE = dico['activer_groupware'] == 'oui'

SUFFIX = dico.get('suffix', 'o=gouv,c=fr')
if LDAP_MODE == 'ad':
    ROOT_DN = 'CN=eole-seth-education,CN=Users,%s' %SUFFIX
else:
    ROOT_DN = 'cn=admin,%s' % SUFFIX
ADMIN_GROUPS = dico.get('admin_groups', ['DomainAdmins', 'PrintOperators'])

#ajoute l'etablissement par défaut si pas spécifié dans le dico
#templatisant la string
class EtabStr(str):
    def __mod__(self, dico):
        dico.setdefault('etab', num_etab)
        if dico['etab'] is None:
            dico['etab'] = num_etab
        return str.__mod__(self, dico)

# dn pour les différentes branches
RACINE = "ou=%s,ou=education,%s" % (acad, SUFFIX)
BRANCHE = "ou=%s,%s" % (num_etab, RACINE)
BRANCHE_ETAB = "ou=%%(etab)s,%s" % (RACINE)
BRANCHE_ETAB2 = EtabStr(BRANCHE_ETAB)
USERS_DN = EtabStr("ou=utilisateurs,%s" % BRANCHE_ETAB)
USER_DN = EtabStr("%s=%%(uid)s,ou=local,ou=%%(_type)s,ou=utilisateurs,%s" % (USER_ATTRIBUTE, BRANCHE_ETAB))
BRANCHE_GROUP_ETAB = "ou=local,ou=groupes,%s" % BRANCHE_ETAB
GROUP_DN = EtabStr("cn=%%(cn)s,%s" % BRANCHE_GROUP_ETAB)
SHARE_DN = EtabStr("cn=smb://%s/%%(share)s,ou=local,ou=partages,%s" % (SMB_SERVEUR, BRANCHE_ETAB))
# filtres pour les differentes branches
USER_FILTER = "(objectclass=inetOrgPerson)(!(description=Computer))"
if LDAP_MODE == 'ad':
    GROUP_FILTER = "(|(&(objectclass=sambaGroupMapping)(objectclass=posixGroup))(&(objectclass=top)(objectclass=group)))"
else:
    GROUP_FILTER = "(&(objectclass=sambaGroupMapping)(objectclass=posixGroup))"
COMPUTER_FILTER = "(description=Computer)(objectclass=posixAccount)"
SHARE_FILTER = "(objectClass=sambaFileShare)"
ELEVE_FILTER = "%s(objectClass=Eleves)" % USER_FILTER
PROF_FILTER = "%s(objectClass=Administrateur)" % USER_FILTER
ADMINISTRATIF_FILTER = "%s(objectClass=administratif)" % USER_FILTER
RESPONSABLE_FILTER = "%s(objectClass=responsable)" % USER_FILTER
AUTRE_FILTER = "%s(objectClass=autre)" % USER_FILTER
# définition des 2 domaines de messagerie
MAIL_DOMAIN = {'restreint' : 'i-{0}'.format(domaine_mess),
               'internet'  : str(domaine_mess)}
MAIL_ADMIN = "admin@{0}".format(MAIL_DOMAIN['internet'])
HAS_SYMPA = dico['has_sympa'] == 'oui'
# définition des éditeurs autorisés
EDITORS_GROUPS = ['professeurs', 'administratifs']
# politique d’envoi par type d’utilisateur
SEND_POLICY = {
        "groupe": "private",
        "option": "private",
        "matiere": "private",
        "classe": "private",
        "niveau": "newsletter",
        "etablissement": "newsletter",
        "resp-classe": "newsletter",
        "resp-groupe": "newsletter",
        "eleves": "newsletter",
        "prof-classe": "editorkey",
        "prof-option": "editorkey",
        "equipe": "editorkey",
        "service": "editorkey",
        "administratifs": "editorkey",
        "professeurs": "editorkey",
        }

# profil Windows disponibles
PROFILS = (('1', 'local'),
           ('4', 'itinérant'),
           ('2', "obligatoire1 (obsolète)"),
           ('3', "obligatoire2 (obsolète)"),
           )
# équivalence entre les différents codes de civilité
CIVILITES = (
             {'code':'1', 'title':'M.', 'sexe':'M'},
             {'code':'2', 'title':'Mme', 'sexe':'F'},
             {'code':'3', 'title':'Mlle', 'sexe':'F'},
            )
# utilisateurs spéciaux à protéger
SPEC_USERS = ['admin', 'user.assr', 'Meta_*', 'Visiteur']

SUPPORT_ETAB = dico['ead_support_multietab'] == 'oui'
EOLE_AD = dico['activer_ad'] == 'oui'
AD_REALM = dico['ad_realm']
AD_ADDRESS = dico['ad_address']
AD_PUBLIC_ADDRESS = dico['ad_public_address']
AD_USERS_ETAB = dico['ad_ou_users_etab']
AD_USER = dico['ad_user']
AD_BASE = ','.join(dico['ad_base'])
AD_PWDFILE = dico['ad_pwdfile']
AD_LDAPS = dico['ad_ldaps'] == 'oui'
MIN_PASSWORD_CLASS = int(dico['smb_min_password_class'])
MIN_PASSWORD_LENGTH = int(dico['smb_min_password_length'])
if LDAP_MODE == 'ad':
    SAMBAPROFILEPATH = 'profilePath'
else:
    SAMBAPROFILEPATH = 'sambaProfilePath'
CONTAINER_NAME = 'domaine'
REVERSE_LOGIN = dico.get('reverse_login', 'non') == 'oui'
REVERSE_LOGIN_DEVOIR = dico.get('reverse_login_devoir', 'non') == 'oui'
