#!/usr/bin/env python
# vim:ts=2:et:sw=2:ai
#
# Build topological network graph
# Rick van der Zwet <info@rickvanderzwet.nl>
import gformat
import sys

from collections import defaultdict

__version__ = '$Id: syntax-checker.py 12574 2013-12-17 20:12:22Z rick $'

allowed_multi_use = ['0.0.0.0', '192.168.1.', '192.168.178.']

def check_double_ip():
  pool = defaultdict(list)
  try:
    for host in gformat.get_hostlist():
      print "## Processing host %-25s: " % host,
      datadump = gformat.get_yaml(host,add_version_info=False)
      try:
        # Process interfaces
        iface_keys = [elem for elem in datadump.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
        for iface_key in iface_keys:
          l = datadump[iface_key]['ip']
          addr, mask = l.split('/')

          pool[addr].append((host, iface_key))

        iface_key = 'masterip'
        addr = datadump['masterip']
        # Add masterip to the list if IP has not been defined at interface
        if not host in [x[0] for x in pool[addr]]:
          pool[addr].append((host, 'masterip'))

        print "OK"
      except (KeyError, ValueError), e:
        print "[ERROR] in '%s' interface '%s' (%s)" % (host, iface_key, e) 
        raise
  except Exception as e:
    raise
    sys.exit(1)

  error = False
  for addr,leden in pool.iteritems():
    if len(leden) > 1:
      if not any(map(lambda x: addr.startswith(x), allowed_multi_use)):
        print "[ERROR] Multiple usages of IP %s:" % (addr)
        for host, key in leden:
          print "  - %s - %s" % (host, key)
        error = True

  if error:
    print "# Errors found"
    return 1
  else:
    print "# No multiple usages of IPs found"
    return 0


if __name__ == "__main__":
  sys.exit(check_double_ip())

