#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Install the pip dependency from source or use the one provided by the system.
Script returns a location to the pip installation, unless it is already
part of the system install.

:author:       Michael Mulich
:copyright:    2010 by Penn State University
:organization: WebLion Group, Penn State University
:license:      GPL, see LICENSE for more detail
"""
import os
import sys
from optparse import OptionParser
from tempfile import mkdtemp
assert sys.version_info >= (2, 7), "Python >= 2.7 is required"
from subprocess import Popen, PIPE

try:
    import pkg_resources
    from setuptools.package_index import PackageIndex
    requirement_parser = pkg_resources.Requirement.parse
except ImportError:
    raise RuntimeError("This installation script require Setuptools "
                       "to be installed prior to the build. Please "
                       "install Setuptools or Distribute before continuing.")

__version__ = '0.1.0'
USAGE = "usage: %prog [options] PIP_VERSION [SRC_DIR]"

def append_to_python_path(entry):
    """Append an entry to the PYTHONPATH environment value."""
    python_path = os.environ.get('PYTHONPATH', None)
    if not python_path:
        python_path = []
    else:
        python_path = python_path.split(os.pathsep)
    if entry not in python_path:
        python_path.append(entry)
    python_path = os.pathsep.join(python_path)
    return python_path

parser = OptionParser(usage=USAGE)
parser.add_option('--build-location', dest='build_location',
                  metavar='LOCATION',
                  default=os.path.abspath(os.curdir),
                  help="a location where pip should be built")

def main():
    options, args = parser.parse_args()
    try:
        pip_version = args[0]
    except IndexError, e:
        parser.print_usage()
        raise RuntimeError('Failed with: %s' % e)
    source = None
    if len(args) > 1:
        source = os.path.realpath(args[1])

    # Check to see if we already have a version of pip we can use.
    has_pip = False
    try:
        pip_reqs = pkg_resources.require('pip>=%s' % pip_version)
    except pkg_resources.VersionConflict:
        pass
    except pkg_resources.DistributionNotFound:
        pass
    else:
        # We already have pip. There is no reason to continue.
        new_path_entry = pip_reqs[0].location
        python_path = append_to_python_path(new_path_entry)
        print('PYTHONPATH=%s' % python_path)
        sys.exit(0)

    install_dir = options.build_location

    # Check to see if pip has already been built.
    pip_install = [i for i in os.listdir(install_dir) if i.startswith('pip')]

    if not pip_install:
        easy_install = 'from setuptools.command.easy_install import main; main()'
        cmd = [sys.executable, '-c', easy_install,
               # easy_install arguments:
               '-mqNxd', install_dir]

        # Provide the source or a requirement line
        if source:
            cmd.append(source)
        else:
            cmd.append('pip==%s' % pip_version)

        # Run easy_install
        p = Popen(cmd, stdout=PIPE)
        comm = p.communicate()

        pip_install = [i
                       for i in os.listdir(install_dir)
                       if i.startswith('pip')]

    # Append it to the python path for environment variable input.
    pip_install = os.path.abspath(os.path.join(install_dir, pip_install[0]))
    python_path = append_to_python_path(pip_install)
    print('PYTHONPATH=%s' % python_path)

if __name__ == '__main__':
    main()
