# -*- encoding: utf-8 -*-

import os
import logging

from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.wrappers import Response

from isso import make_app, wsgi
from isso.core import Config

logger = logging.getLogger("isso")


class Dispatcher(DispatcherMiddleware):
    """
    A dispatcher to support different websites. Dispatches based on
    a relative URI, e.g. /foo.example and /other.bar.
    """

    def __init__(self, *confs):

        self.isso = {}

        for i, conf in enumerate(map(Config.load, confs)):

            if not conf.get("general", "name"):
                logger.warn("unable to dispatch %r, no 'name' set", confs[i])
                continue

            self.isso["/" + conf.get("general", "name")] = make_app(conf)

        super(Dispatcher, self).__init__(self.default, mounts=self.isso)

    def __call__(self, environ, start_response):

        # clear X-Script-Name as the PATH_INFO is already adjusted
        environ.pop('HTTP_X_SCRIPT_NAME', None)

        return super(Dispatcher, self).__call__(environ, start_response)

    def default(self, environ, start_response):
        resp = Response("\n".join(self.isso.keys()), 404, content_type="text/plain")
        return resp(environ, start_response)


if "ISSO_SETTINGS" not in os.environ:
    logger.fatal('no such environment variable: ISSO_SETTINGS')
else:
    confs = os.environ["ISSO_SETTINGS"].split(";")
    for path in confs:
        if not os.path.isfile(path):
            logger.fatal("%s: no such file", path)
            break
    else:
        application = wsgi.SubURI(Dispatcher(*confs))

@@ -20,16 +20,38 @@
 -8 -*-%0A%0A
+from glob import glob%0A
 import o
@@ -1289,20 +1289,16 @@
 ETTINGS%22
- not
  in os.e
@@ -1309,78 +1309,8 @@
 on:%0A
-    logger.fatal('no such environment variable: ISSO_SETTINGS')%0Aelse:%0A
     
@@ -1495,16 +1495,16 @@
   else:%0A
-
         
@@ -1549,8 +1549,293 @@
 confs))%0A
+%0Aelif %22ISSO_SETTINGS_DIR%22 in os.environ:%0A    conf_glob = os.path.join(os.environ%5B%22ISSO_SETTINGS_DIR%22%5D, '*.cfg')%0A    confs = glob(conf_glob)%0A    application = wsgi.SubURI(Dispatcher(*confs))%0A%0Aelse:%0A    logger.fatal('environment variable ISSO_SETTINGS or ISSO_SETTINGS_DIR must be set')%0A

Enable isso settings directory