#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Small WSGI development server based on werkzeug.

Copyright (c) 2008, Florian Wagner <florian@wagner-flo.net>.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""

__version__ = '0.3'

POSSIBILITIES = [
    'app',
    'application'
]

ERROR_USAGE = (1, 'the module option is missing')
ERROR_NOMOD = (2, 'couldn\'t find the given module')
ERROR_NOAPP = (3, 'no application found in module')

CMD_OPTIONS = {
    ('-p', '--port'): {
        'dest': 'port',
        'type': 'int',
        'default': 8080,
        'help': 'port to bind the wsgi server to (default: 8080)' },
    ('-b', '--bind'): {
        'dest': 'host',
        'default': 'localhost',
        'help': ('hostname or IP address to bind the wsgi server to '
                 '(default: localhost)') },
    ('--no-reload',): {
        'dest': 'reload',
        'action': 'store_false',
        'help': 'turn off automatic reloading' },
    ('-a', '--app'): {
        'dest': 'app',
        'help': ('look for variable named APP in module and use as '
                 'served wsgi application') }
}

def print_error(parser, error, with_usage=False):
    status, msg = error

    if with_usage:
        parser.print_help(sys.stderr)
        parser.exit(status, '\nerror: %s\n' % msg)
    
    else:
        parser.exit(status, '%s: error: %s\n' % 
                            (parser.get_prog_name(), msg))

if __name__ == '__main__':
    import sys
    import imp
    import os.path as path
    import optparse
    
    import werkzeug
    
    parser = optparse.OptionParser(usage = 'Usage: %prog [options] module',
                                   version = __version__)

    for opt,kwargs in CMD_OPTIONS.iteritems():
        parser.add_option(*opt, **kwargs)
        
    (options, args) = parser.parse_args()
    
    if len(args) != 1:
        print_error(parser, ERROR_USAGE, with_usage=True)

    try:
        mod = imp.find_module(sys.argv[1], ['.'])
    except ImportError:
        print_error(parser, ERROR_NOMOD)

    mod = imp.load_module(sys.argv[1], *mod)
    app = None
    
    if options.app is None:
        values = POSSIBILITIES[:]
    else:
        values = [options.app]
        
    for value in values:
        app = getattr(mod, value, None)
            
        if app is not None:
            break

    if app is None:
        print_error(parser, ERROR_NOAPP)

    werkzeug.run_simple(options.host, options.port,
                        app, use_reloader = options.reload is None)
