#!/usr/bin/env python

import os
import glob
import pprint

try:
  import yaml
except ImportError, e:
  print e
  print "[ERROR] Please install the python-yaml or devel/py-yaml package"
  exit(1)

try:
    from yaml import CLoader as Loader
    from yaml import CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

NODE_DIR = os.getcwd()
NODE_PREFIX = 'nodes-7-2,'

def get_yaml(item):
  """ Get configuration yaml for 'item'"""
  gfile = NODE_DIR + '/%s/wleiden.yaml' % item

  f = open(gfile, 'r')
  datadump = yaml.load(f,Loader=Loader)
  f.close()

  return datadump

def get_all_configs():
  """ Get dict with key 'host' with all configs present """
  configs = dict()
  for host in get_hostlist():
    datadump = get_yaml(host)
    configs[host] = datadump
  return configs

def get_nodelist():
  """ Get all available nodes - sorted """
  os.chdir(NODE_DIR)
  nodelist = sorted(glob.glob("CNode*"))
  return nodelist

def get_hostlist():
  """ Combined hosts and proxy list"""
  return get_nodelist()

def get_all_configs():
  """ Get dict with key 'host' with all configs present """
  configs = dict()
  for host in get_hostlist():
    datadump = get_yaml(host)
    configs[host] = datadump
  return configs

def is_ileiden(node):
  """ Is this a iLeiden node """
  if (node['ileiden']):
    return str(',nodes-ileiden')
  else:
    return str('')

def get_up_interfaces(node, prefix):
  """ Get nagios syntax for up interlinks """
  iface_up = list()

  for inf in node['interfaces'].split(','):
    iface = 'iface_%s' % inf
    if (node[iface]['status'] == 'up' and is_ap(node[iface])):
      iface_up.append('iface-%s' % inf)
      
  return ','.join(iface_up)

def is_ap(node):
  try:
    if node['dhcp'] == 'no':
      return 1
    else:
      return 0
  except:
    return 0

def is_up(node):
  """ Is node Up?"""
  if node['status'] == 'up':
    return 1
  else:
    return 0

def get_hostname(node):
  return node['nodename']   

def get_ip(node):
  return node['masterip']

def is_iris(node):
  try:
    if node['release'] == '8.0-RELEASE':
      return 1
    elif node['release'] == '7.2-RELEASE':
      return 1
    elif node['release'] == '8.1-RELEASE':
      return 1
    elif node['release'] == '8.2-RELEASE':
      return 1

    return None
  except:
    return 0

def main():
  allconfigs = get_all_configs()
  # pprint.pprint(allconfigs)

  for k,v in allconfigs.iteritems():
    
    if is_iris(v) and is_up(v):
      ileiden = is_ileiden(v)
      interfaces  = get_up_interfaces(v, 'iface-')
      hostname = get_hostname(v)
      ip = get_ip(v)
  
      print """
define host{
  use        host-pnp
  host_name  %s
  alias      %s
  address    %s
  hostgroups %s%s%s
}
  
    """ % (hostname, hostname, ip, NODE_PREFIX, interfaces, ileiden)
 

main()
