#!/usr/bin/env python

##
## GenConfigFiles.py
##      - generated configuration files for Python and PHP from the common metaconfiguration file
##

# $Id: GenConfigFiles.py,v 1.2 2007/01/14 21:53:02 jarda Exp $


# import of required modules {{{
from optparse import OptionParser
import sys
# }}}

g_pythonConfigFileName  = 'BenchConfig.py'
g_pythonClassName       = 'BenchConfig'
g_phpConfigFileName     = 'config.inc.php'
g_phpClassName          = 'BenchConfig'
g_anouncement           = '# This file is generated by GenConfigFiles script and is not supposed to be edited by hand'


def generateConfigFiles():
    # DOC {{{
    """Generates both configuration files.
    """
    # }}}

    # CODE {{{
    parser = OptionParser()

    parser.add_option("-i", "--input-file", dest = "inputFileName",
                      help = "input file name (configuration source)", default = 'config.src')
    parser.add_option("-y", "--python-config-directory", dest = "pythonConfigDirectory",
                      help = "directory in which the python configuration file will be put in", default = '.')
    parser.add_option("-p", "--php-config-directory", dest = "phpConfigDirectory",
                      help = "directory in which the php configuration file will be put in", default = '.')

    (options, args) = parser.parse_args()    

    configurationItems = getConfigurationItems(options.inputFileName)

    if (not configurationItems):
        print >> sys.stderr, 'The configuration file is empty'
    else:
        generatePythonConfigFile(options.pythonConfigDirectory, configurationItems)
        generatePHPConfigFile(options.phpConfigDirectory, configurationItems)
    # }}}


def generatePythonConfigFile(configurationDirectory, configurationItems):
    # DOC {{{
    """Generates Python language configuration file.

    Parameters

        configurationDirectory -- directory that will contain the target file

        configurationItems -- items inserted to the configuration file
    """
    # }}}

    # CODE {{{
    f = open(('%s/%s' % (configurationDirectory, g_pythonConfigFileName,)), 'w')

    lines = []
    lines.append(g_anouncement)
    lines.append('')
    lines.append('class %s(object):' % (g_pythonClassName,))

    maxIdentifierLength = max([len(item[0]) for item in configurationItems])

    equalSignPosition = ((maxIdentifierLength + 1) / 4 * 4) + 4

    if ((maxIdentifierLength + 1) % 4):
        equalSignPosition += 4

    for name, value in configurationItems:
        lines.append('    %s%s= %s' % (name, (equalSignPosition - len(name)) * ' ', value,))

    lines.append('')

    f.write('\n'.join(lines))

    f.close()
    # }}}


def generatePHPConfigFile(configurationDirectory, configurationItems):
    # DOC {{{
    """Generates PHP language configuration file.

    Parameters

        configurationDirectory -- directory that will contain the target file

        configurationItems -- items inserted to the configuration file
    """
    # }}}

    # CODE {{{
    f = open(('%s/%s' % (configurationDirectory, g_phpConfigFileName,)), 'w')

    lines = []
    lines.append('<?php')
    lines.append(g_anouncement)
    lines.append('')
    lines.append('    class %s' % (g_phpClassName,))
    lines.append('    {')

    maxIdentifierLength = max([len(item[0]) for item in configurationItems])

    equalSignPosition = ((maxIdentifierLength + 1) / 4 * 4) + 8

    if ((maxIdentifierLength + 2) % 4):
        equalSignPosition += 4

    for name, value in configurationItems:
        lines.append('        static $%s%s= %s;' % (name, (equalSignPosition - len(name)) * ' ', value,))

    lines.append('    }')
    lines.append('?>')
    lines.append('')

    f.write('\n'.join(lines))

    f.close()
    # }}}


def getConfigurationItems(inputFileName):
    # DOC {{{
    """Extracts configuration items from the metaconfiguration file as a list.

    Parameters

        inputFileName -- the input file name
    """
    # }}}

    # CODE {{{
    f = open(inputFileName)

    itemsList = []

    for line in f:
        line = line.strip()

        if (line[:1] == '#'):
            continue
                
        parts = line.split('=', 1)
        if (len(parts) < 2):
            continue

        firstPart = parts[0].rstrip()
        secondPart = parts[1].lstrip()

        if (firstPart and secondPart):
            itemsList.append((firstPart, secondPart,))

    f.close()

    return itemsList
    # }}}


if (__name__ == '__main__'):
    generateConfigFiles()
