#!/usr/bin/env python

# Copyright (C) 2004-2017 CS-SI. All Rights Reserved.
# Author: Nicolas Delon <nicolas.delon@prelude-ids.com>
#
# This file is part of the Prewikka program.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import ssl
import multiprocessing

from optparse import OptionParser
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, make_server

from prewikka.web import wsgi
from prewikka import siteconfig, main


global options


class WSGIRequest(WSGIRequestHandler):
    def log_message(self, format, *args):
        pass


class MyWSGIServer(WSGIServer):
    def serve_forever(self):
        # Preload Prewikka server
        main.Core.from_config(options.config)

        try:
            WSGIServer.serve_forever(self)
        except KeyboardInterrupt:
            pass


def application(environ, start_response):
    environ["PREWIKKA_CONFIG"] = options.config

    if options.root:
        if not environ['PATH_INFO'].startswith(options.root):
            start_response('301 Redirect', [('Location', options.root), ])
            return []

        environ['SCRIPT_NAME'] = options.root[:-1]
        environ['PATH_INFO'] = environ['PATH_INFO'][len(options.root) - 1:]

    return wsgi.application(environ, start_response)


if __name__ == "__main__":
    parser = OptionParser(epilog=" ")

    parser.add_option("-r", "--root", action="store", type="string", dest="root", default="", help="Root where the server is accessible")
    parser.add_option("-a", "--address", action="store", type="string", dest="addr", default="0.0.0.0", help="IP to bind to (default: %default)")
    parser.add_option("-p", "--port", action="store", type="int", dest="port", default=8000, help="port number to use (default: %default)")
    parser.add_option("", "--key", action="store", type="string", dest="key", default=None, help="SSL private key to use (default: no SSL)")
    parser.add_option("", "--cert", action="store", type="string", dest="cert", default=None, help="SSL certificate to use (default: no SSL)")
    parser.add_option("-c", "--config", action="store", type="string", dest="config", default="%s/prewikka.conf" % siteconfig.conf_dir, help="configuration file to use (default: %default)")
    parser.add_option("-m", "--multiprocess", action="store", type="int", dest="num_process", default=multiprocessing.cpu_count(),
                      help="number of processes to use. Default value matches the number of available CPUs (i.e. %d)" % multiprocessing.cpu_count())

    (options, args) = parser.parse_args()

    if options.root:
        options.root = "/%s/" % (options.root.strip("/"))

    server = make_server(options.addr, options.port, application, server_class=MyWSGIServer, handler_class=WSGIRequest)
    if options.key and options.cert:
        server.socket = ssl.wrap_socket(server.socket, keyfile=options.key, certfile=options.cert, server_side=True)

    for i in range(options.num_process - 1):
        p = multiprocessing.Process(target=server.serve_forever)
        p.daemon = True

        p.start()

    server.serve_forever()

