#!/usr/bin/env python
#############################################################################
# This program is part of Zenoss Core, an open source monitoring platform.
# Copyright (C) 2007, Zenoss Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# For complete information please visit: http://www.zenoss.com/oss/
#############################################################################

import os
import urllib2
import re
import unicodedata

# Bail out if ZENHOME is not set.
if 'ZENHOME' not in os.environ:
    print "ZENHOME is not set. Run this command as the zenoss user."
    sys.exit(1)


# Attempt to download the latest enterprise assignments from IANA.
iana_url = "http://www.iana.org/assignments/enterprise-numbers"
iana_prefix = ".1.3.6.1.4.1"

try:
    instream = urllib2.urlopen(iana_url)
except IOError:
    print "Unable to retrieve OIDs from IANA."
    print "  - %s" % iana_url
    sys.exit(1)

content = instream.read()
instream.close()

# Open the dynamically generated module.
filename=os.path.join(os.environ['ZENHOME'],
    "Products/DataCollector/EnterpriseOIDs.py")

fo = open(filename, "wb")
fo.write("# This module was dynamically generated by the buildEnterpriseOids.py script.\n")
fo.write("# The data is obtained from http://www.iana.org/assignments/enterprise-numbers\n\n")
fo.write("EnterpriseOIDs = {\n")

newline = re.compile(r'\n')
numbers = re.compile(r'^[0-9]+')
blanks = re.compile(r'^\s+$')
split_contents = newline.split(content)
key=None
for line in split_contents:
    m = numbers.search(line)
    if m:
        if line != "0":
            key = line

    if key and not m:
        # Convert unicode strings to ascii .. dropping unicode chars ...
        val = unicodedata.normalize('NFKD',
            unicode(line)).encode('ascii','ignore')
        n = blanks.search(val)
        if n:
            val = None
        if val:
            # Strip leading blanks.
            val = re.sub("^\s+","",val)
            
            # Strip control characters.
            val = re.sub(r"[^\w!.,<>@#$%^&*\/()]", " ", val)
            
            # Escape single and double quotes.
            val = val.replace('"', '\\"').replace("'", "\\'")
            
            fo.write("    '%s.%s': '%s',\n" % (iana_prefix, key, val))
        key = None

fo.write("    }\n")
fo.close()
print "IANA enterprise OID mappings written to module."
print "  %s" % filename
