#!/usr/bin/env python

# Copyright (C) 2004-2020 CS GROUP - France. 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 argparse
import locale
import multiprocessing
import socket
import ssl
import sys

from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server

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

global options


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


class MyWSGIServer(WSGIServer):
    def handle_error(self, request, client_address):
        exc_type, exc_value = sys.exc_info()[:2]
        if issubclass(exc_type, socket.error) and exc_value.args[0] == 32:  # EPIPE
            return

        WSGIServer.handle_error(self, request, client_address)

    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)


def set_locale(lang):
    if lang[0] not in localization.get_languages():
        lang = "en_GB.utf8"
    else:
        lang = ".".join(lang)

    localization.translation.set_locale(lang)


if __name__ == "__main__":
    set_locale(locale.getdefaultlocale())

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument("-r", "--root", help=_("root where the server is accessible"))
    parser.add_argument("-a", "--address", default="0.0.0.0", help=_("IP to bind to (default: %(default)s)"))
    parser.add_argument("-p", "--port", type=int, default=8000, help=_("port number to use (default: %(default)d)"))
    parser.add_argument("--key", help=_("SSL private key to use (default: no SSL)"))
    parser.add_argument("--cert", help=_("SSL certificate to use (default: no SSL)"))
    parser.add_argument("-c", "--config", default="%s/prewikka.conf" % siteconfig.conf_dir, help=_("configuration file to use (default: %(default)s)"))
    parser.add_argument("-m", "--multiprocess", type=int, default=multiprocessing.cpu_count(),
                        help=_("number of processes to use. Default value matches the number of available CPUs (i.e. %d)") % multiprocessing.cpu_count())
    parser.add_argument("-h", "--help", action="help", help=_("show this help message and exit"))
    parser.add_argument("-v", "--version", action="version", version=version.__version__, help=_("show program's version number and exit"))

    options = parser.parse_args()

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

    server = make_server(options.address, 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)
        server.base_environ["HTTPS"] = "on"  # This is used by wsgiref to determine url_scheme

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

        p.start()

    server.serve_forever()
