#!/usr/bin/env python
"""Module ldap"""
import sys
from glob import glob
from shutil import copyfile
from os import unlink, makedirs, stat
from os.path import dirname, isdir, isfile
from creole.client import CreoleClient
from pyeole.process import system_code
from pyeole.service import manage_service
from pyeole.bareosrestore import bareos_restore_one_file, exit_if_running_jobs

LDAPFILE = '/home/backup/sauv_ldap.ldif'

def execute(option, opt_str, value, parser, jobid, test_jobs=True):
    """ldap helper"""
    if len(parser.rargs) > 0:
        option = parser.rargs[0]
        if option == 'pre':
            pre()
        elif option == 'post':
            post()
    else:
        if test_jobs:
            exit_if_running_jobs()
        job(jobid)

def pre():
    print("pre ldap")

def post():
    print("post ldap")
    if not isfile(LDAPFILE):
        print("Il manque le fichier {0}".format(LDAPFILE))
        sys.exit(1)
    if stat(LDAPFILE).st_size == 0:
        print("Le fichier {0} est vide".format(LDAPFILE))
        sys.exit(1)
    path = CreoleClient().get_creole('container_path_annuaire')
    if path != '':
        # copie du ldif dans le conteneur
        destdir = path + dirname(LDAPFILE)
        if not isdir(destdir):
            makedirs(destdir)
        copyfile(LDAPFILE, path + LDAPFILE)
    manage_service('stop', 'slapd', 'annuaire')
    system_code(["sleep", "5"])
    for files in glob("{0}/var/lib/ldap/*.*".format(path)):
        unlink(files)
    slapadd_cmd = ['/usr/sbin/slapadd', '-f', '/etc/ldap/slapd.conf',
                   '-l', LDAPFILE]
    system_code(slapadd_cmd , container='annuaire')
    system_code(["chown", "-R", "openldap:openldap", "/var/lib/ldap"],
                 container='annuaire')
    manage_service('start', 'slapd', 'annuaire')

def job(jobid):
    print("Restauration de l'annuaire LDAP")
    bareos_restore_one_file(LDAPFILE, jobid)

priority = 20
