#!/usr/bin/env python2.3
"""
Keep It Simple, Stupid automatic WSDL generation tool.

For generating syntactically correct doc/lit WSDL from 
a simple configuration file (in the format recognized by ConfigParser).
"""
__author__ = "Dan Gunter"
__email__ = "dkgunter@lbl.gov"
__version__ = "0.1"

from ConfigParser import SafeConfigParser
import logging
from optparse import OptionParser
import sys

class ConfigError(Exception):
    def __init__(self,msg):
        Exception.__init__(self,"Missing the %s parameter" % msg)

def slurp(filename):
    f = open(filename)
    chunk_list = []
    while 1:
        chunk = f.read()
        if chunk == '': break
        chunk_list.append(chunk)
    return ''.join(chunk_list)

def generateWsdl(wsdl_template,wsdl_output,mapping):
    outf = open(wsdl_output + ".wsdl","w")
    try:
        outf.write(slurp(wsdl_template) % mapping)
    except KeyError,E:
        e = str(E)
        raise ConfigError(e)
    logging.info("Wrote file '%s'" % outf.name)
    
def run(config_file,wsdl_template):
    logging.info("Using config file '%s' and WSDL template '%s'" %
                 (config_file,wsdl_template))
    cfgfile = open(config_file)
    parser = SafeConfigParser()
    parser.readfp(cfgfile)    
    for section in parser.sections():
        logging.info("Processing section %s" % section)
        generateWsdl(wsdl_template,section,dict(parser.items(section)))

def main(cmdline):
    DEFAULT_TMPL = "template.wsdl"
    logging.basicConfig()
    parser = OptionParser(usage="%prog [options] config-file",
                          version=__version__)
    parser.add_option("-t", "--template", dest="wsdl_template",
                      default=DEFAULT_TMPL,metavar="FILE",
                      help="Use wsdl template FILE (%s)" % DEFAULT_TMPL)
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="Don't print status messages to stdout")
    (options, args) = parser.parse_args(cmdline[1:])
    if len(args) < 1:
        parser.error("Configuration file is required")
    if len(args) > 1:
        parser.error("Extra arguments after configuration file")
    # logging
    if options.verbose:
        logging.getLogger().setLevel(logging.INFO)
    else:
        logging.getLogger().setLevel(logging.WARN)
    # run
    try:
        run(args[0],options.wsdl_template)
        logging.info("No errors")
    except ConfigError,E:
        logging.error("Configuration error: %s" % E)
    
if __name__ == '__main__': main(sys.argv)

    

