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

__version__ = '$Id: syntax-checker.py 10904 2012-05-18 21:48:21Z rick $'

allowed_multi_use = ['0.0.0.0', '192.168.1.100']

def check_double_ip():
  pool = {}
  try:
    for host in gformat.get_hostlist():
      print "## Processing host %-20s: " % host,
      datadump = gformat.get_yaml(host,add_version_info=False)
      try:
        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('/')

          label = "%s - %s" % (host, iface_key)
          if pool.has_key(addr): 
            pool[addr] += [label]
          else: 
            pool[addr] = [label]
        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 addr in allowed_multi_use:
        print "[ERROR] Multiple usages of IP %s:" % (addr)
        print "  -", "\n  - ".join(leden)
        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())

