#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-
#
# Service in charge of firewall for trigger.
# Contains multiple subservices for each special
# part of firewall.
#
# Author  : Pierre-Elliott Bécue <becue@crans.org>
# Licence : GPLv3
# Date    : 15/06/2014
"""
Firewall service module. is uses the firewall library as it's, it
is not designed to replace it, just to call specific functions from
it to regenerate what needs to.
"""

import cranslib.clogger as clogger
import gestion.config.trigger as trigger_config
logger = clogger.CLogger("trigger", "firewall", trigger_config.log_level, trigger_config.debug)

from gestion.trigger.host import record_service
import gestion.trigger.firewall4.firewall4 as firewall4

class FwFactory(object):
    """Records firewall functions, and provide them.

    """

    _fwfuns = {}

    @classmethod
    def register(cls, key, value):
        cls._fwfuns[key] = value

    @classmethod
    def get(cls, key):
        return cls._fwfuns.get(key, None)

def fwrecord(fun):
    FwFactory.register(fun.func_name, fun)

@record_service()
def firewall(ob_id, operations=()):
    """Regens the specific service

    """
    if len(operations) != 2:
        logger.warning("Received operations %r, this format is incorrect, discarding.", operations)
        return
    (service, data) = operations
    logger.info("Calling service %s for data %r", service, data)
    # XXX - Uncomment when in prod
    #FwFactory.get(service)(data)

@fwrecord
def mac_ip(operations):
    host_fw = firewall4.firewall()
    if operations and isinstance(operations, dict):
        for (mac, ip) in operations.get("add", []):
            logger.info("Adding mac_ip %s,%s", mac, ip)
            host_fw.mac_ip_append(mac, ip)
        for (mac, ip) in operations.get("delete", []):
            logger.info("Removing mac_ip %s,%s", mac, ip)
            host_fw.mac_ip_remove(mac, ip)
        for (rmac, rip, mac, ip) in operations.get("update", []):
            logger.info("Updating mac_ip %s,%s with %s,%s", rmac, rip, mac, ip)
            host_fw.mac_ip_remove(rmac, rip)
            host_fw.mac_ip_append(mac, ip)
