# -*- coding: utf-8 -*-
###########################################################################
# Eole NG - 2009
# Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
# Licence CeCill  cf /root/LicenceEole.txt
# eole@ac-dijon.fr
#
###########################################################################
"""
    interface de gestion des user 'administratifs'
"""
from os import makedirs
from os.path import join, isdir
from ldap import MOD_REPLACE
from fichier.quota import set_quota
from fichier.acl import set_owner, clear_acl, set_user_acl, copy_default_acl
from scribe.ldapconf import SMB_SERVEUR, HOME_PATH, MAIL_DOMAIN, \
ADMINISTRATIF_FILTER, AD_HOME_PATH
from scribe.eoletools import replace_cars, create_ad_home, \
format_current_date, not_empty, to_list
from scribe.eoleuser import User, gen_common_attrs, send_first_mail, \
gen_profil, gen_radius_attrs

class Administratif(User):
    """
        classe pour la gestion des personnels administratifs
    """
    _type = 'personnels'
    profil = 'administratif'
    filtre = "(&%s)" % ADMINISTRATIF_FILTER
    must_args = ['login', 'password', 'nom', 'prenom', 'date', 'civilite']
    may_args = dict(mail='internet',
                    quota='0',
                    profil='1',
                    shell=False,
                    change_pwd=False,
                    mail_acad='',
                    int_id='',
                    groupe='',
                    entlogin=True,
                    etab=None,
                    entpersonjointure='',
                    syncpassword=True,
                   )
    has_samba = True
    has_ftp = True

    def get_smbldap_useradd_args(self, login,  profil, shell, groupe, **args):
        """
            ajoute un utilisateur à l'aide /usr/sbin/smbldap-useradd
        """
        if shell:
            shell = "bash"
        else:
            shell = "false"
        groups = to_list(groupe)
        groups.append('DomainUsers')
        useradd_args = ['-o', 'ou=local,ou=personnels',
                        '-s', '/bin/%s' % shell,
                        '-d', '/home/%s/%s' % (login[0], login),
                        '-C', '\\\\{0}\\{1}\\perso'.format(SMB_SERVEUR, login),
                        '-F', '%s' % gen_profil(profil, login),
                        '-g', 'administratifs',
                        '-G', ','.join(groups),
                        login]
        return useradd_args

    def _add_scribe_user(self, login, **args):
        """
            ajout les attributs Scribe à un Administratif
        """
        mail = args['mail']
        if '@' not in mail:
            if mail in ['internet', 'restreint']:
                mail = "{0}@{1}".format(login, MAIL_DOMAIN[mail])
                maildir = self.get_maildir(login)
            else:
                mail = ''
                maildir = ''
        else:
            maildir = ''
        # Rappel : 0-> prof normal, 1-> utilisateur admin,
        #          2-> prof principal, 3-> administratifs
        typeadmin = '3'
        datas = []
        user_dn = self.get_user_dn(login) #USER_DN % dict(uid=login, _type=self._type)
        objectclass = self._get_attr(login, 'objectClass')
        objectclass.extend(['administratif', 'ENTPerson',
            'ENTAuxNonEnsEtab', 'radiusprofile'])
        datas.append((MOD_REPLACE, 'objectClass', objectclass))
        datas.extend(gen_common_attrs(login, entprofil=self.profil, **args))
        datas.extend(gen_radius_attrs())
        if mail != '':
            datas.append((MOD_REPLACE, 'mail', mail))
        if maildir != '':
            datas.append((MOD_REPLACE, 'mailHost', 'localhost'))
            datas.append((MOD_REPLACE, 'mailDir', maildir))
        datas.append((MOD_REPLACE, 'typeadmin', typeadmin))
        if not_empty(args, 'mail_acad'):
            datas.append((MOD_REPLACE, 'FederationKey',
                          args['mail_acad'].lower()))
        # FIXME : remplissage d'attributs provenant de ENTAuxNonEnsEtab
        self.ldap_admin._modify(user_dn, datas)
        if maildir != '':
            send_first_mail(mail)

    def _add_perso(self, login, **args):
        """
            Crée les différents répertoires de l'utilisateur
        """
        abc = join(HOME_PATH, login[0])
        rep = join(abc, login)
        perso = join(rep, 'perso')
        # Eole-AD
        create_ad_home(login, rep)
        if not isdir(perso):
            makedirs(perso, 0o700)
        rep = join(AD_HOME_PATH, login)
        # répertoire supérieur
        clear_acl(rep)
        set_user_acl(rep, login, 'rwx')
        copy_default_acl(rep)
        # chown pour la prise en compte des quotas
        set_owner(perso, login)
        if 'quota' in args:
            set_quota(login, args['quota'])

    def _update(self, login, **args):
        """
            Mise à niveau Administratif via l'extraction
        """
        user_dn = self.get_user_dn(login) #USER_DN % dict(uid=login, _type=self._type)
        datas = []
        if not_empty(args, 'mail_acad'):
            datas.append((MOD_REPLACE, 'FederationKey',
                          args['mail_acad'].lower()))
        if not_empty(args, 'int_id'):
            datas.append((MOD_REPLACE, 'intid', args['int_id'] ))
        if not_empty(args, 'entpersonjointure'):
            datas.append((MOD_REPLACE, 'ENTPersonJointure', args['entpersonjointure']))
        datas.append((MOD_REPLACE, 'sn', args['nom']))
        datas.append((MOD_REPLACE, 'givenName', args['prenom']))
        datas.append((MOD_REPLACE, 'cn', "%(prenom)s %(nom)s" % args ))
        datas.append((MOD_REPLACE, 'displayName', "%(prenom)s %(nom)s" % args ))
        datas.append((MOD_REPLACE, 'gecos', replace_cars("%(prenom)s %(nom)s" % args) ))
        datas.append((MOD_REPLACE, 'LastUpdate', format_current_date()))
        self.ldap_admin._modify(user_dn, datas)

    def _get_administratifs(self, attrs=['uid']):
        return self._get_users(filtre=self.filtre, attrs=attrs)

    def _is_administratif(self, uid):
        """
            test si l'utilisateur existe dans l'annuaire
        """
        uidfilter = "(&%s(uid=%s))" % (ADMINISTRATIF_FILTER, uid)
        if self.ldap_admin._search_one(uidfilter):
            return True
        return False
