#!/usr/bin/python2.6
import os
import sys
import site

def _prepare_sys_path():
    """
    Add Zope2 paths which must be after current working directory
    *and* PYTHONPATH but before other paths, otherwise it would
    conflict with already installed Debian packages of Zope.

    Only using addsitedir() is not enough as it appends to sys.path,
    thus Zope paths would end up at the end.
    """
    # Always insert after the current working directory
    insert_zope_path_index = 1

    # If PYTHONPATH is defined, then get the last position of
    # PYTHONPATH path within sys.path
    PYTHONPATH = os.getenv('PYTHONPATH')
    if PYTHONPATH:
        PYTHONPATH = PYTHONPATH.split(os.pathsep)

        import re

        # Prepare the regex to match existing sys.path
        for index, path in enumerate(PYTHONPATH):
            if path[-1] == os.sep:
                path = path[:-1]

            PYTHONPATH[index] = re.escape(path)

        PYTHONPATH_RE = re.compile("(%s)" % '|'.join(PYTHONPATH))
        for path in sys.path[1:]:
            if not PYTHONPATH_RE.match(path):
                break

            insert_zope_path_index += 1

    # All paths besides of current working directory and PYTHONPATH
    other_sys_path = sys.path[insert_zope_path_index:]

    # Only keep current working directory and PYTHONPATH and then add
    # Zope paths (addsitedir() only append to sys.path)
    sys.path[insert_zope_path_index:] = []

    instance = os.getenv('INSTANCE_HOME')
    if instance:
        site.addsitedir(instance + '/lib/python')
    site.addsitedir('/usr/lib/zope2.12/lib/python')

    sys.path.extend(other_sys_path)

_prepare_sys_path()
del _prepare_sys_path

sys.executable = os.path.abspath(__file__)

_interactive = True
if len(sys.argv) > 1:
    _options, _args = __import__("getopt").getopt(sys.argv[1:], 'ic:m:')
    _interactive = False
    for (_opt, _val) in _options:
        if _opt == '-i':
            _interactive = True
        elif _opt == '-c':
            exec _val
        elif _opt == '-m':
            sys.argv[1:] = _args
            _args = []
            __import__("runpy").run_module(
                 _val, {}, "__main__", alter_sys=True)

    if _args:
        sys.argv[:] = _args
        __file__ = _args[0]
        del _options, _args
        execfile(__file__)

if _interactive:
    del _interactive
    __import__("code").interact(banner="", local=globals())
