#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4

import greenlet
import eventlet
import logging
import os
import signal
import sys

# If ../keystone/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(__file__),
                                   os.pardir,
                                   os.pardir))
if os.path.exists(os.path.join(possible_topdir,
                               'keystone',
                               '__init__.py')):
    sys.path.insert(0, possible_topdir)


from paste import deploy

from keystone import config
from keystone.common import wsgi
from keystone.common import utils
from keystone.openstack.common import importutils


CONF = config.CONF


def create_server(conf, name, host, port):
    app = deploy.loadapp('config:%s' % conf, name=name)
    server = wsgi.Server(app, host=host, port=port)
    if CONF.ssl.enable:
        server.set_ssl(CONF.ssl.certfile, CONF.ssl.keyfile,
                       CONF.ssl.ca_certs, CONF.ssl.cert_required)
    return server


def sigint_handler(signal, frame):
    """Exits at SIGINT signal."""
    logging.debug('SIGINT received, stopping servers.')
    sys.exit(0)


def serve(*servers):
    signal.signal(signal.SIGINT, sigint_handler)

    for server in servers:
        server.start()

    # notify calling process we are ready to serve
    if CONF.onready:
        try:
            notifier = importutils.import_module(CONF.onready)
            notifier.notify()
        except ImportError:
            try:
                utils.check_output(CONF.onready.split())
            except Exception:
                logging.exception('Failed to execute onready command')

    for server in servers:
        try:
            server.wait()
        except greenlet.GreenletExit:
            pass


if __name__ == '__main__':
    dev_conf = os.path.join(possible_topdir,
                            'etc',
                            'keystone.conf')
    config_files = None
    if os.path.exists(dev_conf):
        config_files = [dev_conf]

    CONF(project='keystone', default_config_files=config_files)

    config.setup_logging(CONF)

    # Log the options used when starting if we're in debug mode...
    if CONF.debug:
        CONF.log_opt_values(logging.getLogger(CONF.prog), logging.DEBUG)

    if not CONF.config_file:
        print "No config files could be found."
        CONF.print_help()
        sys.exit(1)

    monkeypatch_thread = not CONF._cli_values['standard_threads']
    eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
                                  thread=monkeypatch_thread)

    options = deploy.appconfig('config:%s' % CONF.config_file[0])

    servers = []
    servers.append(create_server(CONF.config_file[0],
                                 'admin',
                                 CONF.bind_host,
                                 int(CONF.admin_port)))
    servers.append(create_server(CONF.config_file[0],
                                 'main',
                                 CONF.bind_host,
                                 int(CONF.public_port)))
    serve(*servers)
