import os
import subprocess
import sys
import waeup.stress
from optparse import OptionParser
from ConfigParser import SafeConfigParser

VALID_MODES = ('paster', 'kofactl', 'zeo', 'profile')

def configure_options():
    usage = 'Usage: %prog <project name> [options]'
    parser = OptionParser(usage=usage)
    parser.add_option('-p', '--port', dest='port', type='int',
                      help='rpc listener port')
    parser.add_option('-r', '--results', dest='results_dir',
                      help='results directory to reprocess')
    parser.add_option('-b', '--bind-addr', dest='bind_addr',
                      help='rpc bind address', default='localhost')
    parser.add_option('-d', '--directory', dest='projects_dir',
                      help='directory containing project folder', default='.')
    cmd_opts, args = parser.parse_args()

    try:
        project_name = args[0]
    except IndexError:
        sys.stderr.write('\nERROR: no project specified\n\n')
        sys.stderr.write('%s\n' % usage)
        sys.stderr.write('Example: multimech-run my_project\n\n')
        sys.exit(1)
        pass

    return cmd_opts, args

DEFAULTS = dict(
    instance='kofa', baseport='8080', server_port='8100',
    zope_threads='10', cache='20MB', cached_objs='5000',
    paster_threads='10', use_threadpool='true', buildout='',
    instance_mode='paster', start_instance='true', host='localhost')

def configure_project(name, path):
    """Parse project in `path` with name `name`.

    Extracts kofa-related settings and returns them as a dict.
    """
    print "CONFIGURE PROJECT: ", name, path
    cfg_path = os.path.join(path, 'config.cfg')
    cfg_defaults = dict([('kofa_' + name, value)
                         for name, value in DEFAULTS.items()])
    config = SafeConfigParser(cfg_defaults)
    config.read(cfg_path)
    params = dict()
    params.update(DEFAULTS)
    for name, value in config.items('global'):
        if not name.startswith('kofa_'):
            continue
        name = name.split('_', 1)[-1]
        print name, value
        params.update(dict({name: value}))
    if params['instance_mode'] not in VALID_MODES:
        print "Warning: invalid instance_mode in config.cfg, picking 'paster'."
        print "  valid would be: %s" % VALID_MODES
        params['instance_mode'] = 'paster'
    params['start_instance'] = config.getboolean(
        'global', 'kofa_start_instance')
    return params

def configure():
    cmd_opts, args = configure_options()
    project_name = args[0]
    path = os.path.abspath(os.path.join(cmd_opts.projects_dir, project_name))
    cfg_opts = configure_project(project_name, path)
    return path, project_name, cmd_opts, cfg_opts

def main():
    path, project_name, cmd_opts, cfg_opts = configure()
    pre_run_path = os.path.join(path, 'pre_run.py')
    post_run_path = os.path.join(path, 'post_run.py')
    sys.path.append(path) # make project scripts available for import
    if os.path.exists(pre_run_path):
        print "WAEUP.STRESS.RUN: running pre_run %s" % pre_run_path
        execfile(pre_run_path)
    # late import as this scripts mangles sys.argv
    from multimechanize.utilities import run
    run.main()
    if os.path.exists(post_run_path):
        print "WAEUP.STRESS.RUN: running post_run %s" % post_run_path
        execfile(post_run_path)
    return
