#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from IPy import IP
from glob import glob
from os import makedirs, unlink
from os.path import join, isdir, isfile
from pyeole.service import manage_services
from creole.client import CreoleClient
from creole.eosfunc import is_ip

DHCP_DIR = 'etc/dhcp/fixed-address'
CONFIG_FILE = '/var/lib/eole/config/dhcp.conf'
DHCP_TMPL = "host %s { hardware ethernet %s; fixed-address %s; }\n"
DICO = CreoleClient().get_creole()

def build_dir_name():
    """
    Calcul du chemin du répertoire en fonction du mode
    conteneur/non conteneur
    """
    return join('/', DICO['container_path_dhcp'], DHCP_DIR)

def build_file_name(network, netmask):
    """
    Calcul du chemin de l'un des fichiers de configuration
    """
    dirname = build_dir_name()
    return join(dirname, network+"_"+netmask+'.txt')

def clean():
    """
    remove old files and create empty files
    """
    dirname = build_dir_name()
    if not isdir(dirname):
        makedirs(dirname)
    for name in glob(join(dirname, '*')):
        unlink(name)
    for i in range(0, len(DICO['adresse_network_dhcp'])):
        network = DICO['adresse_network_dhcp'][i]
        netmask = DICO['adresse_network_dhcp.adresse_netmask_dhcp'][i]
        file_name = build_file_name(network, netmask)
        fh = open(file_name, 'w+')
        fh.write('')
        fh.close()

def gen_dhcp_config(tupples_fixed_address):
    """
    Génération de la configuration
    """
    names = []
    mac_addrs = []
    ip_addrs = []
    for name, ip, mac in tupples_fixed_address:
        subnet_found = False
        if name in names:
            print "Le nom {0} est déjà présent".format(name)
            continue
        names.append(name)
        if mac in mac_addrs:
            print "L'adresse MAC {0} est déjà présente".format(mac)
            continue
        mac_addrs.append(mac)
        if not is_ip(ip):
            print "L'adresse IP {0} n'est pas une adresse valide".format(ip)
            continue
        if ip in ip_addrs:
            print "L'adresse IP {0} est déjà présente".format(ip)
            continue
        ip_addrs.append(ip)
        for i in range(0, len(DICO['adresse_network_dhcp'])):
            network = DICO['adresse_network_dhcp'][i]
            netmask = DICO['adresse_network_dhcp.adresse_netmask_dhcp'][i]
            file_name = build_file_name(network, netmask)
            subnet_ip = IP('{0}/{1}'.format(network, netmask))
            if ip in subnet_ip:
                fh = open(file_name, 'a')
                fh.write(DHCP_TMPL % (name, mac, ip))
                fh.close()
                subnet_found = True
                break
        if not subnet_found:
            print "Aucun subnet n'est déclaré pour cette adresse IP : {0} ({1})".format(ip, name)

def read_ead_config():
    """
    lecture des adresses configurées dans l'EAD
    """
    tupples_fixed_address = []
    if isfile(CONFIG_FILE):
        for line in file(CONFIG_FILE).read().splitlines():
            if line.count('#') == 2:
                tupples_fixed_address.append(line.split('#'))
    return tupples_fixed_address

if __name__ == '__main__':
    clean()
    gen_dhcp_config(read_ead_config())
    if len(sys.argv) == 1:
        # si aucun argument, on redémarre le service
        ret = manage_services('restart', 'isc-dhcp-server', 'dhcp')
        if ret != 0:
            print "Une erreur s'est produite au redémarrage du service dhcp"
        exit(ret)
