#!/usr/bin/env python3
from lxml.etree import Element, SubElement, tostring
import ldap

conf_file = '/var/lib/eole/config/wpkg.cfg'
exec(open(conf_file).read())

# Open the LDAP connection
try:
    ldap.set_option(ldap.OPT_REFERRALS, 0)
    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
    l = ldap.initialize(f'ldaps://{AD_HOST_NAME}:636')
    #  recuperation du mot de passe de eole-workstation-reader
    with open(LDAP_PWD, 'r') as reader:
        user_pwd = reader.readline().strip()
    l.simple_bind_s(LDAP_BIND, user_pwd)
except ldap.LDAPError as e:
    print(f'unable to connect or bind user to LDAP {e}')
    exit(1)

# Build XML content from LDAP informations
xml = Element('wpkg')
try:
    res = l.search_s(BASEDN,
                     ldap.SCOPE_SUBTREE,
                     '(&(objectclass=computer))',
                     ['name', 'canonicalName'],
                     )
    for (dn, vals) in res:
        if isinstance(vals, list):
            continue
        accountname = vals['name'][0].decode().lower()
        if accountname in [AD_HOST_NAME, NOM_MACHINE]:
            continue
        ou = vals['canonicalName'][0].decode().lower()
        # remove domainname and computer name
        ou = '-'.join(ou.split('/')[1:-1])
        # replace space to _
        ou = ou.replace(' ','_')
        sub = SubElement(xml, 'host', name=accountname)
        sub.attrib['profile-id'] = ou
    l.unbind_s()
except ldap.LDAPError as error_message:
    print(error_message)

# Write file
with open(HOSTS_XML, 'w') as xmlfh:
    xmlfh.write(tostring(xml,
                         pretty_print=True,
                         encoding="UTF-8",
                         xml_declaration=True,
                         ).decode())
