#!/usr/bin/env python
#
# Copyright (c) 2012 SEOmoz
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os
import argparse

# Read in some of our arguments
parser = argparse.ArgumentParser(description='Run a HTTP server, serving ASIS files stored in a directory')

parser.add_argument('path', default='.', type=str, nargs='?',
    help='The path of the stored As-Is files')
parser.add_argument('--port', dest='port', default=80, type=int,
    help='The port to run the server on')
parser.add_argument('--daemonize', dest='daemonize', action='store_true',
    help='Daemonize the server')
parser.add_argument('--server', dest='server', default='wsgiref', type=str,
    help='Which server backend to use (gevent, twisted, etc.)')
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
    help='Be extra talkative')

args = parser.parse_args()

# If the server is gevent, we have to monkey patch before we import bottle
if args.server == 'gevent':
    from gevent import monkey
    monkey.patch_all()

# /Now/ we can import asis if we need to
import asis

if args.verbose:
    import logging
    asis.logger.setLevel(logging.DEBUG)

# Let's be safe and use an absolute path here
path = os.path.abspath(args.path)

# And what mode are we starting this thing up in?
mode = 'block'
if args.daemonize:
    mode = 'fork'

# Now run the damned thing
asis.Server(path, args.port, args.server, mode).run()
