#!/usr/bin/python
# -*- coding: utf-8 -*-
#
##########################################################################
# python-pyeole
# Copyright © 2015 Pôle de compétences EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
##########################################################################
from os.path import join, isdir, isfile
from xml.etree import ElementTree as ET
from grp import getgrnam
from pwd import getpwnam
from pyeole.log import init_logging
import posix1e
from creole.client import CreoleClient

client = CreoleClient()

if client.get_creole('activer_esu') == "oui":
    log = init_logging(name=u'05-esu', level='info', syslog=False,
                       console=['stdout', 'stderr'])

    XMLDIR = "/home/esu/Base"
    filename = join(XMLDIR, "ListeGM.xml")
    xml = ET.parse(filename)
    for group in xml.getiterator('GM'):
        esu_group_name = group.get('nom')
        filename = join(XMLDIR, esu_group_name, "_ListeUtilisateurs.xml")
        if not isfile(filename):
            log.error('file {} is not already exists'.format(filename))
            continue
        xml = ET.parse(filename)
        for groupe in xml.getiterator('GU'):
            name = groupe.get('nom')
            try:
                if groupe.get('type') == 'U':
                    #if group is an user
                    posix_id = getpwnam(name).pw_uid
                    posix_type = posix1e.ACL_USER
                else:
                    #if group is a group
                    posix_id = getgrnam(name).gr_gid
                    posix_type = posix1e.ACL_GROUP
            except KeyError:
                #user does not exists
                log.error('user or group {} does not exists'.format(name))
                continue
            #get directory informatin
            dirname = join('/home/netlogon/icones', esu_group_name, name)
            if not isdir(dirname):
                log.error('directory {} not already exists'.format(dirname))
                continue
            #if right not correct, change it
            acls = posix1e.ACL(file=dirname.encode("utf-8"))
            found = False
            for acl in acls:  # get_acl(dirname)
                if acl.tag_type == posix_type and acl.qualifier == posix_id:
                    if not acl.permset.read or not acl.permset.execute:
                        acl.permset.read = True
                        acl.permset.execute = True
                        acls.applyto(dirname)
                    found = True
                elif acl.tag_type == posix1e.ACL_OTHER and str(acl.permset) != '---':
                    acl.permset.read = False
                    acl.permset.execute = False
                    acl.permset.write = False
                    acls.applyto(dirname)

            if not found:
                acl = acls.append()
                acl.tag_type = posix_type
                acl.qualifier = posix_id
                acl.permset.read = True
                acl.permset.execute = True
                acls.calc_mask()
                acls.applyto(dirname)
