#!/usr/local/bin/python

import sys,string,fileinput,re,getopt

oc_def = {}
keepers = {}
flounder = ""
#process command line input
#takes a single command "--use-list=<filename>" the rest of the
#command line consists of filenames of LDAP oc files.
#
#the use list is a list of object classes that will be selected from
#the input and processed into the Python output.  If the use list does
#not exist, all of the object classes found in the input files will be
#processed into the Python output.

try:
     options, arguments = getopt.getopt(sys.argv[1:],'',['use-list='])
except Exception, flounder:
     print "occonf2ldapoc.py [--use-list=<filename>] file1 file2 ... fileN"
     print flounder
     sys.exit(0)

if len(options)!=0:
     #process the "keepers list".  The below is a hack based on the
     #fact that I know I will only have one option on the command
     #line.
     #
     #print type(options[0]), options
     [command, data] = options[0]
     #print "command = ", command
     try:
          #print "data = ", data
          for line in fileinput.input(data):
               if re.match("^\s*#", line):
                    #we have a comment so throwaway the line
                    #print "thrown away -->", line
                    continue
               else:
                    # otherwise strip off all the blanks and store in a
                    # dictionary. 
                    keepers[string.strip(line)] = ' '
               
     except Exception, cod:
          print cod
          print "data = ", data
          sys.exit (0)

#print keepers, len(keepers)
#  print len(arguments)
#  print arguments
#  print len(options)
#  print options


for s in fileinput.input(arguments):

     #the first thing to do is throwaway the comment characters
     #sys.stderr.write("?-> "+ s)
     if re.match("^\s*#", s):
          continue

     #otherwise continue processing the file as normal
     #sys.stderr.write("k-> "+ s)
     slist = string.split(string.strip(s),' ')
     keyword = string.lower(slist[0])

     if keyword=='objectclass':
          if len(slist)==2:
               oc = string.strip(slist[1])
               label = ''
               oc_def[oc] = {'requires':[],'allows':[]}
          elif label:
               oc_def[oc][label].append(slist[0])
  
     elif keyword=='requires' or keyword=='allows':
          label = slist[0]

     elif slist[0]:
          if slist[0][-1]==',':
               slist[0]=slist[0][:-1]
          
          oc_def[oc][label].append(slist[0])

#now, in the output stage of this program, Python code is created
#based on what LDAP objects are found in the input files.  This is
#modified somewhat by the presence of a keeper's list.  A keeper's
#list states what LDAP objects should be printed.  All other objects
#are ignored.

#a couple of notes about where to place the filter.  It turns out that
#filtering on either input or output is a royal Bear.  In both places
#there are special processing requirements  and I think I can decode
#the output better than I can the input section hence my placing of
#the filtering in output.

outfile = sys.stdout

outfile.write('ldap_oc = {\n')

#filter the keys before iterating through the list
oc_list = []

for key in oc_def.keys():
     if len(keepers) != 0:
          if keepers.has_key(key):
               oc_list.append(key)

     else:
          #nothing in the keepers list so just append it anyway
          oc_list.append(key)

for oc in oc_list[:-1]:
     
     outfile.write("""'%s':{
     'requires':%s,
     'allows':%s
     },
     """ % (oc,oc_def[oc]['requires'],oc_def[oc]['allows']))

oc=oc_list[-1]
outfile.write("""  '%s':{
     'requires':%s,
     'allows':%s
     }
""" % (oc,oc_def[oc]['requires'],oc_def[oc]['allows']))

outfile.write('}\n')

outfile.close()
