#!/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

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

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  %(name)s
  alias      %(name)s
  address    %(ns_ip)s
  hostgroups %(hostgroups)s
}
""" % datadump


if __name__ == '__main__':
  # Process all hosts
  for host in gformat.get_hostlist():
    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']:
      hostgroups.append('nano5')

      # Interface groups
      for iface in datadump['autogen_iface_keys']:
        ifacedump = datadump[iface]
        try:
          if not ifacedump['mode'] == 'ap' and is_up(ifacedump):
            ifacedump['use'] = 'host-pnp'
            ifacedump['name'] = "%s-%s" % (host, ifacedump['autogen_ifname'])
            ifacedump['ns_ip'] = ifacedump['ns_ip'].split('/')[0]
            key = 'iface-%s' % ifacedump['autogen_ifname']
            print_host(ifacedump, hostgroups)
        except:
          continue

