#!/usr/bin/python
# -*- coding:utf-8 -*-

# Author: Pablo Saavedra Rodinho
# Contact: pablo.saavedra@interoud.com

"""
Save a group of streams from http or udp and generates a db with related info

"""

from optparse import OptionParser

import os
import sys
import subprocess

reload(sys)
sys.setdefaultencoding('utf-8')

import ConfigParser
import simplejson as json


import time
from datetime import datetime
import struct
import socket

import urllib2
import httplib2

DEV_NULL=open('/dev/null', "w")

conffile = "./checker.cfg"

logfile = "/dev/stdout"
loglevel = 20
workdir = "./checker/"

_template = '''<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>2.0</version>
    <date>2013-07-25T22:04:07Z</date>
    <groups>
        <group>
            <name>Templates</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>Template_Sources</template>
            <name>Template_Sources</name>
            <groups>
                <group>
                    <name>Templates</name>
                </group>
            </groups>
            <applications/>
            <items>
            %(items)s
            </items>
            <discovery_rules/>
            <macros/>
            <templates/>
            <screens/>
        </template>
    </templates>
    <triggers>
    %(triggers)s
    </triggers>
</zabbix_export>

'''

_i = '''
                <item>
                    <name>stream $1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>stream[%(key)s]</key>
                    <delay>180</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>4</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications/>
                    <valuemap/>
                </item>
'''

_t = '''
        <trigger>
            <expression>{Template_Sources:stream[%(key)s].diff(0)}=1 | {Template_Sources:stream[%(key)s].str([Ok])}=0</expression>
            <name>%(key)s down on {HOST.NAME}</name>
            <url/>
            <status>0</status>
            <priority>4</priority>
            <description/>
            <type>0</type>
            <dependencies/>
        </trigger>
'''


# command line options parser ##################################################

parser = OptionParser()

parser.add_option("-f", "--file", dest="conffile",
        help="The configuration file (default: %s)" % conffile,
        default=conffile)
parser.add_option("-l", "--logfile",
        dest="logfile", help="Log file (default: %s)" % logfile,
        default=logfile)
parser.add_option("--loglevel",
        dest="loglevel", help="Log level (default: %s)" % loglevel,
        default=loglevel)
(options, args) = parser.parse_args()

conffile = options.conffile

logfile = options.logfile
loglevel = options.loglevel



# logging ######################################################################
import logging
hdlr = logging.FileHandler(logfile)
hdlr.setFormatter(logging.Formatter('%(levelname)s %(asctime)s %(message)s'))
logger = logging.getLogger('fluunt')
logger.addHandler(hdlr)
logger.setLevel(int(loglevel))


# setting up ###################################################################

logger.info("Default encoding: %s" % sys.getdefaultencoding())

################################################################################


def main():
    global conffile
    '''
['key_http']
uri="http://localhost:8082"
protocol="http"
chunkduration=30
quantity=100

['key_udp']
ip="127.0.0.1"
port=1234
protocol="udp"
chunkduration=30
quantity=1000
    '''



    res = {}

    try:
      # RawConfigParser not interpolate attribute values
      cfg = ConfigParser.RawConfigParser()
      cfg.readfp(file(conffile))

    except Exception, e:
        print ("Conffile %s error: %s" % (conffile,e))

    items = ""
    triggers = ""

    for s in cfg.sections():
        key = s
        try:
          uri = None
          ip = None
          port = None
          chunkduration = 10
          protocol = None
          quantity = 1
          if s == 'global':
              for o in cfg.options(s):
                  try:
                      vars()[o] = cfg.get(s,o)
                  except Exception, e:
                      print "Error parsing %s - %s: %s" % (s,o,e)
              continue

          for o in cfg.options(s):
              uri = eval (cfg.get(s,o)) if o == 'uri' else uri
              ip = eval (cfg.get(s,o)) if o == 'ip' else ip
              port = eval (cfg.get(s,o)) if o == 'port' else port
              chunkduration = eval (cfg.get(s,o)) if o == 'chunkduration' else chunkduration
              protocol = eval (cfg.get(s,o)) if o == 'protocol' else protocol
              quantity = eval (cfg.get(s,o)) if o == 'quantity' else quantity

          items += _i % {"key": key}
          triggers += _t % {"key": key }
        except Exception, e:
          logger.error ("Problem on %s stream: %s" % (key,e))

    print _template % {"items":items, "triggers":triggers}

# main #########################################################################

if __name__ == '__main__':
    main()

