# -*- coding: utf-8 -*-

"""
Classe de synchronisation entre la base ldap et
la base postgresql pour la liste des exemptions
et la liste des machines.
Utilisé par generate.py
"""

# importation des fonctions et classes

import sys
if '/usr/scripts' not in sys.path:
    sys.path.append('/usr/scripts')
import lc_ldap.shortcuts
import lc_ldap.objets
from gestion.gen_confs import gen_config
import psycopg2

ldap_conn = lc_ldap.shortcuts.lc_ldap_readonly()

# Génération des la tables d'exemptions
#######################################

class exemptions(gen_config):
    base = [('138.231.136.0/24', '0.0.0.0/0'), ('138.231.136.0/21', '138.231.0.0/16'), ('138.231.144.0/21', '138.231.0.0/16')]
    restart_cmd = ""

    def __str__(self):
        return "filtrage_exemptions"

    def _gen(self):
        machines = ldap_conn.search(u'(exempt=*)', sizelimit=9999)
        pgsql = psycopg2.connect(database='filtrage', user='crans')
        curseur = pgsql.cursor()

        # Purge.
        requete = "DELETE FROM exemptes"
        curseur.execute(requete)

        for source, destination in self.base:
            requete = "INSERT INTO exemptes (ip_crans, ip_dest) VALUES ('%s','%s')" % (source, destination)
            curseur.execute(requete)

        for machine in machines:
            for destination in machine["exempt"]:
                if destination.value.version == 4:
                    source = str(machine["ipHostNumber"][0])
                    requete = "INSERT INTO exemptes (ip_crans, ip_dest) VALUES ('%s','%s')" % (source, destination)
                else:
                    source = str(machine["macAddress"][0])
                    requete = "INSERT INTO exemptes6 (mac_crans, ip_dest) VALUES ('%s','%s')" % (source, destination)
                # Si ip vide, passons au suivant
                if not source:
                    continue
                curseur.execute(requete)

        pgsql.commit()

# Génération des la liste des machines
######################################

class machines(gen_config):
    restart_cmd = ""
    def __str__(self):
        return "filtrage_machines"

    def _gen(self):
        machines = ldap_conn.search(u"(ipHostNumber=*)", sizelimit=9999)

        # liste des machines (on prend que les paimement ok)
        # machines = self.machines
        # machines = db.search('ip=*')['machine']

        # connexion à la base postgresql
        pgsql = psycopg2.connect(database='filtrage', user='crans')
        curseur = pgsql.cursor()
        curseur.execute("DELETE FROM machines;")

        # ajout des entrée
        for m in machines:
            if m.proprio().__class__ == lc_ldap.objets.club:
                if not m['macAddress'][0].value == '<automatique>':
                    curseur.execute("INSERT INTO machines (mac_addr, type, id) VALUES ('%s','club',%s);" % (m['macAddress'][0], m.proprio()['cid'][0].value))
            elif m.proprio().__class__ == lc_ldap.objets.adherent:
                if not m['macAddress'][0].value == '<automatique>':
                    curseur.execute("INSERT INTO machines (mac_addr, type, id) VALUES ('%s','adherent',%s);" % (m['macAddress'][0], m.proprio()['aid'][0].value))
            elif m.proprio().__class__ == lc_ldap.objets.AssociationCrans:
                curseur.execute("INSERT INTO machines (mac_addr, type, id) VALUES ('%s','crans',%s);" % (m['macAddress'][0], m['mid'][0].value))
        # on commit
        pgsql.commit()

