#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2014 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)
"""Machinery entry point -- to be run from in-repo location"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"

import sys
from inspect import getabsfile
from os.path import abspath, basename, dirname, join, realpath
from os import listdir


# inspired by http://stackoverflow.com/a/22881871
def get_script_path(follow_symlinks=True):
    if getattr(sys, 'frozen', False):  # PyInstaller, cx_Freeze
        path = abspath(sys.executable)
    else:
        path = getabsfile(get_script_path)
    return path

script_path = get_script_path()
real_script_path = realpath(script_path)


if (basename(real_script_path) != basename(sys.argv[0])
    and 'LOGSKIP' not in globals()):
    # when execfile'd from tests or so, verbose logging desired
    from os import environ
    import logging
    logging.basicConfig()
    logging.getLogger().setLevel(environ.get('LOGLEVEL') or logging.DEBUG)

root = dirname(real_script_path)

# XXX very similar to setup.py, but better
self_discovery_plan = [join(root, '__project__')]
while True:
    pkg = {}
    maybe_root = self_discovery_plan.pop()
    maybe_root_real = realpath(maybe_root)
    maybe_root = basename(maybe_root)
    try:
        sys.path.insert(0, dirname(maybe_root_real))
        pkg = __import__(basename(maybe_root_real), globals=pkg, level=1)
        break
    except ImportError:
        sys.path.pop(0)
        if maybe_root == '__project__':
            from fnmatch import filter as fnfilter
            self_discovery_plan.extend(p[:-len('.egg-info')].split('-', 1)[0]
                                       for p in fnfilter(listdir(root),
                                                         '*.egg-info'))
        if not self_discovery_plan:
            print "Cannot find myself, please help me with __project__ symlink"
            raise

# set the correct __package__ for relative imports
__package__ = basename(maybe_root_real)  # XXX optionally strip whole '-..' part
if __package__ not in sys.modules:
    sys.modules[__package__] = pkg

if __name__ == '__main__':
    if basename(real_script_path) == basename(sys.argv[0]):  # __file__ undef?
        from . import __main__

# XXX previous attempt to get unittest.main executed automagically at the end,
#     which was failing likely because unittest uses Threading that register
#     another atexit handler somehow interfering w/ its main started from here
#    elif ('tests' == basename(dirname(script_path))
#          == basename(dirname(abspath(__file__))):
#        from atexit import register
#        from unittest import main
#        register(main)
#        # hmm, see https://code.google.com/p/modwsgi/issues/detail?id=197
#        # https://github.com/GrahamDumpleton/mod_wsgi/commit/fdef274
#        register(lambda: __import__('dummy_threading'))
