'''
A script used to extract almost all constants from C header files (*.h).

(c) 2007-2009 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or 
 (at your option) any later version.

'''

import re, sys

reg_define = re.compile(
  r'^#define\s+(CL_)([A-Z0-9a-z_]+)\s+(.*)$'
)
reg_enum_start = re.compile(
  r'^(typedef +)?enum +([a-z0-9_]*) *{*'
)
reg_enum_end = re.compile(
  r'^} *[a-z0-9_]*;$'
)

if len(sys.argv)>1:
  sys.stdout = open(sys.argv[1], 'wt')

if len(sys.argv)>2:
  clamav_h = open(sys.argv[2], 'rt')
else:
  clamav_h = open('/usr/include/clamav.h', 'rt')

print """\
# This file is automatically generated by getconst.py.
CL_CLEAN = 0
"""
enum_block = 0
for line in clamav_h.readlines():
  # handle comments and trailing new lines
  line = line.strip().replace('/*', '# /*')
  # enum block
  if enum_block==0 and reg_enum_start.search(line):
    print "# enum block:", line
    print "("
    enum_block += 1
    continue
  if enum_block>0 and reg_enum_end.search(line):
    print ") = range(%d)" % enum_block
    print "# enum block:", line
    enum_block = 0
    continue
  if enum_block>0:
    if line=='CL_CLEAN = 0,':
      continue
    if line=='CL_SUCCESS = 0,':
      line = 'CL_SUCCESS,'
    enum_block += line.split('#',1)[0].count(',')
    print "  "+line
  # search for #define line
  r = reg_define.search(line)
  if r:
    print "%s%s = %s" % r.groups()
    #print "%s = %s" % (r.group(2), r.group(3))

# add section to remove CL_ prefix for all constants
print """
for key, value in globals().items():
  if key.startswith("CL_") and (key[3:] not in globals()):
      exec("%s = %s" % (key[3:], key))
"""
