#!/usr/bin/env python
# Copyright 2011 Canonical Ltd.
#
# This file is part of u1db.
#
# u1db is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# u1db is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with u1db.  If not, see <http://www.gnu.org/licenses/>.

import sys

from u1db import (
    __version__ as _u1db_version,
    )
from u1db.commandline import (
    serve,
    )


def main(args):
    import argparse
    p = argparse.ArgumentParser(usage='%(prog)s [options]',
        description='Run the U1DB server')
    p.add_argument('--version', action='version', version=_u1db_version)
    p.add_argument('--verbose', action='store_true', help='be chatty')
    p.add_argument('--host', '-H', default='127.0.0.1', metavar='HOST',
                   help='Bind on this host when serving.')
    p.add_argument('--port', '-p', default=0, metavar='PORT', type=int,
        help='Bind to this port when serving.')
    p.add_argument('--working-dir', default='.', metavar='WORKING_DIR',
                   help='Directory where the databases live.')
    p.add_argument('--accept-cors-connections', default=None,
                   metavar="ACCEPTED_ORIGINS",
                   help='Comma separated accepted origins or "*"')

    args = p.parse_args(args)
    accept_cors_connections = args.accept_cors_connections
    if accept_cors_connections is not None:
        accept_cors_connections = accept_cors_connections.split(',')
    server = serve.make_server(args.host, args.port, args.working_dir,
                               accept_cors_connections)
    sys.stdout.write('listening on: %s:%s\n' % server.server_address)
    sys.stdout.flush()
    server.serve_forever()


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


# vim: ft=python
