#!/usr/bin/env python
#
# Script to create nagios output files from gformat configurtion files
#
# Original: Richard van Mansom <richardvm@wirelessleiden.nl>
# Rick van der Zwet <rick@wirelessleiden.nl>

import gformat
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

def is_ap(ifacedump):
#  return ifacedump.has_key('dhcp') and not ifacedump['dhcp'] == 'no'
  return ifacedump.has_key('dhcp') and not ifacedump['dhcp'] == False

def is_iris(node):
  return node.has_key('release') and node['release'] in ['8.0-RELEASE', '7.2-RELEASE', '8.1-RELEASE', '8.2-RELEASE', '9.0-RELEASE']

def is_up(datadump):
  return datadump['status'] == 'up'



def print_host(datadump, hostgroups):
  datadump['hostgroups'] = ','.join(hostgroups)
  print """
define host{
  use        %(use)s
  host_name  %(autogen_realname)s
  alias      %(autogen_realname)s
  address    %(masterip)s
  hostgroups %(hostgroups)s
}
""" % datadump


if __name__ == '__main__':
  # Process all hosts
  for host in gformat.get_hostlist():
    logger.debug("Processing host %s", host)
    datadump = gformat.get_yaml(host)

    # Make sure to process only active IRIS nodes
    if not is_iris(datadump) or not is_up(datadump):
      continue

    hostgroups = []
    if datadump['nodetype'] in ['CNode', 'Hybrid']:
      datadump['use'] = 'host-pnp'
      hostgroups.append('nodes-7-2')

      # Interface groups
      for iface in datadump['autogen_iface_keys']:
        ifacedump = datadump[iface]
        if is_up(ifacedump) and not is_ap(ifacedump):
          key = 'iface-%s' % ifacedump['autogen_ifname']
          if not key in hostgroups:
            hostgroups.append(key)

      # ileiden groups
#     if datadump['ileiden'] or datadump['nodetype'] == "Hybrid":
      if datadump['nodetype'] in ['CNode', 'Hybrid']:
        datadump['use'] = 'host-pnp'
        hostgroups.append('nodes-ileiden')

        print_host(datadump, hostgroups)
      elif datadump['nodetype'] == 'Proxy':
        datadump['use'] = 'host-proxy'
        hostgroups.append('proxies')

        print_host(datadump, hostgroups)
      else:
        print "# ERROR: nodetype %(nodetype)s for %(autogen_realname)s not defined" % datadump



