import os
import sys
from os import path

# Constants
DIRTY_BUILD_INFO = []
VERSION = "1.4.3"
BUILD_NUMBER = "1072"
COMMIT_HASH = "49f7c9dff5e319ddedb46ee7089140e0156e7376"
CACHED_ENV_PREFIX = "XPYV_ORIG_"
DEBUG = False

# Module globals (Initialized at end of module)
original_environ = None

def get_unmodified_environment():
    """
    Returns the environment without the modifications
    """
    original_environ = dict()
    for env_name, env_value in os.environ.iteritems():
        if env_name.startswith(CACHED_ENV_PREFIX):
            continue
        original_env_name = CACHED_ENV_PREFIX + env_name
        original_env_value = os.environ.get(original_env_name)
        if original_env_value is None:
            original_environ[env_name] = os.environ[env_name]
        elif original_env_value not in ('(none)', '(null)'):
            original_environ[env_name] = original_env_value
    return original_environ

if os.environ.has_key("XPYV_DEBUG"):
    DEBUG = True

# Initialize globals
original_environ = get_unmodified_environment()
XPYV_HOME = sys.exec_prefix

if not os.environ.has_key("XPYV_DIRTY_ENV"):
    if DEBUG:
        sys.stderr.write("Restoring original environment\n")
    STARTUP_ENVIRON = dict(os.environ)
    for env_name, env_value in original_environ.iteritems():
        os.environ[env_name] = env_value
    for env_name in os.environ.keys():
        if not original_environ.has_key(env_name):
            os.environ.pop(env_name)

if path.basename(sys.executable) == "python.bin":
    sys.executable = path.join(path.dirname(sys.executable), "xpyv")
if path.basename(sys.executable) == "python.exe":
    sys.executable = path.join(path.dirname(sys.executable), "xpyv.cmd")

_xpyv_path = os.environ.get("XPYVPATH")
if (_xpyv_path):
    sys.path[:0] = _xpyv_path.split(os.pathsep)

def versions_compare(version1, version2):
    """
    Compare two version names.

    @type version1: str
    @type version2: str

    @return Negative if version1 < version2, zero if version1==version2, positive if version1 > version2.
    @see pkg_resources.parse_version() (from setuptools)
    """
    # Import has to be done after sys.path is updated.
    from pkg_resources import parse_version

    return cmp(parse_version(version1), parse_version(version2))
