#!/usr/bin/python

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

"""
This module forwards all filtered datas to another shinken
This is useful to create "real-test traffic"
"""

from subprocess import Popen
from shinken.basemodule import BaseModule
from shinken.log import logger

properties = {
    'daemons': ['broker'],
    'type': 'checks-forward',
    'external': True,
}

def get_instance(mod_conf):
    instance = Checkforward(mod_conf)
    return instance

class Checkforward(BaseModule):
    def __init__(self, mod_conf):
        BaseModule.__init__(self, mod_conf)
        logger.info("[Checks forward] module init")

        try:
            logger.debug("[Checks forward] module init : get parameters entities")

            # Module configuration
            self.glpi_entities = getattr(mod_conf, 'glpi_entities', '')
            self.glpi_entities = self.glpi_entities.split(',')
            if len(self.glpi_entities) > 0 and self.glpi_entities[0] == '':
                self.glpi_entities = None

            logger.warning("[Checks forward] module init : get parameters nsca")
            self.send_nsca_bin = str(getattr(mod_conf, 'send_nsca_bin', '/usr/sbin/send_nsca'))
            self.send_nsca_config = str(getattr(mod_conf, 'send_nsca_config', '/etc/send_nsca.cfg'))

            logger.warning("[Checks forward] module init : get parameters nsca server")
            self.nsca_server_host = str(getattr(mod_conf, 'nsca_server_host', '127.0.0.1'))
            self.nsca_server_port = int(getattr(mod_conf, 'nsca_server_port', 5667))

            logger.warning("[Checks forward] module init : log info")
            logger.info("[Checks forward] module configuration, forward to: %s:%s, using %s with configuration %s" % (self.nsca_server_host, self.nsca_server_port, self.send_nsca_bin, self.send_nsca_config))
            if self.glpi_entities:
                logger.info("[Checks forward] module configuration, forward checks for GLPI entities: %s" % str(self.glpi_entities))
            else:
                logger.info("[Checks forward] module configuration, forward checks for all hosts/services")

            # Internal cache for host entities id
            self.cache_host_entities_id = {}
        except AttributeError:
            logger.error("[Checks forward] The module is missing a property, check module configuration")
            raise
        
    def init(self):
        logger.debug("[Checks forward] init function")

    def manage_initial_host_status_brok(self, b):
        # if not self.glpi_entities:
        #     return

        # self.cache_host_entities_id[b.data['host_name']] = -1
        try:
            logger.warning("[Checks forward] initial host status: %s" % str(b.data['customs']))
            self.cache_host_entities_id[b.data['host_name']] = b.data['customs']['_ENTITIESID']
            if self.cache_host_entities_id[b.data['host_name']] in self.glpi_entities:
                logger.info("[Checks forward] host %s checks will be forwarded (entity: %s)" % (b.data['host_name'], self.cache_host_entities_id[b.data['host_name']]))
        except:
            logger.error("[Checks forward] Error in initial_host_status")
        
    def manage_host_check_result_brok(self, b):
        try:
            if self.glpi_entities and self.cache_host_entities_id[b.data['host_name']] not in self.glpi_entities:
                return
        except:
            return
        
        try:
            self.send_nsca(b)
        except OSError as e:
            logger.error("[Checks forward] Error forward nsca '%s'" % e)

    def manage_service_check_result_brok(self, b):
        try:
            if self.glpi_entities and self.cache_host_entities_id[b.data['host_name']] not in self.glpi_entities:
                return
        except:
            return

        try:
            self.send_nsca(b)
        except OSError as e:
            logger.error("[Checks forward] Error forward nsca '%s'" % e)
            

    def send_nsca(self, b):
        check_type = b.type
        hostname = b.data['host_name']
        return_code = b.data['return_code']
        output = b.data['output']

        if (check_type == "service_check_result"):
            service_description = b.data['service_description']
            # <hostname>[TAB]<service name>[TAB]<return code>[TAB]<plugin output>
            send_nsca = hostname+"\t"+service_description+"\t"+str(return_code)+"\t"+output+"|"+b.data['perf_data']
        if (check_type == "host_check_result"):
            # <hostname>[TAB]<return code>[TAB]<plugin output>
            send_nsca = hostname+"\t"+str(return_code)+"\t"+output+"|"+b.data['perf_data']

        logger.warning("[Checks forward] sending nsca '%s' for '%s'" % (check_type,hostname))
        command = "/bin/echo \"%s\" | %s -H %s -p %s -c %s" % (send_nsca, self.send_nsca_bin, self.nsca_server_host, self.nsca_server_port, self.send_nsca_config)
        try:
            retcode = Popen(command, shell=True)
            return True
        except:
            return False

    def manage_brok(self, b):
        if b.type in ('initial_host_status', 'initial_service_status', 'service_check_result', 'host_check_result'):
            BaseModule.manage_brok(self, b)

    def main(self):
        self.set_proctitle(self.name)
        self.set_exit_handler()
        while not self.interrupted:
            l = self.to_q.get()
            for b in l:
                b.prepare()
                self.manage_brok(b)

@@ -596,16 +596,26 @@
 ule init
+ialization
 %22)%0A%0A    
@@ -627,92 +627,8 @@
 ry:%0A
-            logger.debug(%22%5BChecks forward%5D module init : get parameters entities%22)%0A%0A
     
@@ -916,89 +916,8 @@
 ne%0A%0A
-            logger.warning(%22%5BChecks forward%5D module init : get parameters nsca%22)%0A
     
@@ -1114,96 +1114,8 @@
 ))%0A%0A
-            logger.warning(%22%5BChecks forward%5D module init : get parameters nsca server%22)%0A
     
@@ -1292,78 +1292,8 @@
 ))%0A%0A
-            logger.warning(%22%5BChecks forward%5D module init : log info%22)%0A
     
@@ -2180,131 +2180,8 @@
 b):%0A
-        # if not self.glpi_entities:%0A        #     return%0A%0A        # self.cache_host_entities_id%5Bb.data%5B'host_name'%5D%5D = -1%0A
     
@@ -2200,38 +2200,36 @@
          logger.
-warnin
+debu
 g(%22%5BChecks forwa
@@ -2661,37 +2661,39 @@
          logger.
-error
+warning
 (%22%5BChecks forwar
@@ -2699,37 +2699,58 @@
 rd%5D 
-Error in initial_host_status%22
+no entity Id for host: %25s%22 %25 (b.data%5B'host_name'%5D)
 )%0A  
@@ -4237,38 +4237,36 @@
 %0A        logger.
-warnin
+debu
 g(%22%5BChecks forwa

Clean logs .... warning to debug