#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-
#
# DHCP's trigger parser.
#
# Author : Pierre-Elliott Bécue <becue@crans.org>
# Licence : GPLv3
# Date : 19/11/2014
#
"""
Handles the parser for trigger about dhcp service
This currently is used for mac/IP updates of LDAP database.
"""

import lc_ldap.attributs as attributs
from gestion.trigger.host import record_parser, chaining

@record_parser(attributs.macAddress, attributs.ipHostNumber)
@chaining(1)
def dhcp(ob_id, operations, diff, more):
    """Computes mac_ip data to send from operations and diff

    The dict contains lists of tuples, so we can iterate on them
    in the service."""
    macs = tuple([operations[i].get(lc_ldap.attributs.macAddress.ldap_name, [''])[0] for i in xrange(0, 2)])
    ips = tuple([operations[i].get(lc_ldap.attributs.ipHostNumber.ldap_name, [''])[0] for i in xrange(0, 2)])
    hostnames = tuple([operations[i].get(lc_ldap.attributs.host.ldap_name, [''])[0] for i in xrange(0, 2)])

    # Régénération du DHCP :
    if not macs[0]:
        # Création d'une nouvelle machine.
        dhcp_dict = {'add': [(macs[1], ips[1], hostnames[1])]}
    elif not macs[1]:
        # Destruction d'une machine.
        dhcp_dict = {'delete': [(macs[0], ips[0])]}
    else:
        # Mise à jour.
        dhcp_dict = {'update': [(macs[0], ips[0], macs[1], ips[1], hostnames[1])]}
    return ("dhcp", dhcp_dict)
