#!/usr/bin/env python2
from fileinput import filename

SOFT           = "Org.Asm"
LIB            = "orgasm"
PIP_MINVERSION = '1.5'
MODE           = "svn" # or "pypi"
SVNURL         = "http://www.grenoble.prabi.fr/public-svn/LECASofts/orgasm/trunk"


ZIPFILE ="""\
[encoded data, 2865709 characters]
aXR5LnB5VVQFAAOGTy5UdXgLAAEE9QEAAAQUAAAAUEsFBgAAAACXAZcBWqoAAF20HwAAAA==\
"""

install_script="""\
#!/bin/bash

binpath='%s/bin'
system=`uname -s`

if [ "$system" == "Darwin" ]
then
    loginshell=`dscl . -read /Users/\`whoami\` UserShell | awk '{print $NF}'`
    parent=`"$binpath/pidname" $PPID | awk '{print $NF}'`
else
    loginshell=`getent passwd \`whoami\` | awk -F ':' '{print $NF}'`
    parent=`readlink /proc/$PPID/exe`
fi

if [[ "$parent" == *"login" ]]
then
    target=$loginshell
else
    target=$parent
fi

echo    
echo You can now use %s
echo


if [[ "$target" == *"csh" ]]
then
    activate="$binpath/activate.csh"
else
    activate="$binpath/activate"
fi

    $target -c "source \\"$activate\\"; $target"

echo    
echo %s are no more activated, Bye...
echo

"""

local_pip=[]


import base64
import os.path
import shutil
import sys
import tempfile
import urllib2
import imp
import zipimport
import importlib
import glob
import tarfile
import pkgutil
import stat

from distutils.errors import DistutilsError
from distutils.version import LooseVersion

tmpdir = []

def getTmpDir():
    global tmpdir

    if not tmpdir:
        tmpdir.append(tempfile.mkdtemp())
        
    return tmpdir[0]


def installModules():
    global LIB
    global SOFT

    tmpdir=getTmpDir()

    try:

        # Unpack the zipfile into the temporary directory
        install_zip = os.path.join(tmpdir, "%s.zip" % LIB)
        with open(install_zip, "wb") as fp:
            fp.write(base64.decodestring(ZIPFILE))

        # Add the zipfile to sys.path so that we can import it
        sys.path.insert(0,install_zip)

    except:
        print >>sys.stderr,'Unable to install %s on your system' % SOFT
        
    print install_zip
        
def cleanModules():

    if tmpdir:
            shutil.rmtree(tmpdir[0], ignore_errors=True)
           
def is_pip_installed(minversion=PIP_MINVERSION):
    try:
        import pip  # @UnresolvedImport
        print pip.__file__
        ok = LooseVersion(pip.__version__) >= LooseVersion(minversion)
    except:
        ok = False
        
    return ok

def get_a_pip_module(minversion=PIP_MINVERSION):
    
    global local_pip
        
    tmpdir = getTmpDir()
    
    if not local_pip: 
        pipmodule = importlib.import_module('pip') 
            
        # Prepare the CERT certificat for https download
            
        cert_path = os.path.join(tmpdir, "cacert.pem")
        
        with open(cert_path, "wb") as cert:
            cert.write(pkgutil.get_data("pip._vendor.requests", "cacert.pem"))
            
        os.environ.setdefault("PIP_CERT", cert_path)
        
        local_pip.append(pipmodule)
       
    return local_pip[0]


def pip_download_package(package,pip=None):
    tmpdir = getTmpDir()

    if pip is None:
        pip = get_a_pip_module()
                
    args = ['install']
    
    if 'http_proxy' in os.environ:
        args.append('--proxy=%s' % os.environ['http_proxy'])
        
    args.append('--download=%s' % tmpdir)
    args.append('--index-url=https://pypi.python.org/simple/')
    args.append('--no-deps')
    args.append('-I')
    
    args.append(package)
        
    pip.main(args)

    filename = glob.glob(os.path.join(tmpdir,"%s*" % package))[0]
    tar = tarfile.open(filename)
    tar.extractall(tmpdir)
    dir = os.path.splitext(os.path.splitext(filename)[0])[0]
    
    return dir

# pip install --download="titi" --no-deps -I obitools 

def svndownload():
    global SVNURL
    global LIB
    
    import svn.remote  # @UnresolvedImport
   
    rc = svn.remote.RemoteClient(SVNURL)
    filename = "%s/%s" % (getTmpDir(),LIB)
    
    rc.export(filename)

    return filename
    
def pypidownload():
    global SOFT
    
    pip = get_a_pip_module()
    filename=pip_download_package(SOFT,pip=pip)
    
    return filename
            
def main():
    global SVNURL
    global LIB
    global SOFT
    
    installModules()
    
    if MODE=="svn":
        filename = svndownload()
    elif MODE=='pypi':
        filename = pypidownload()
        
    sys.path.insert(0, filename)
    
    import setup  # @UnresolvedImport

    current = os.getcwd()
    
    virtualenvname = "%s/%s-%s" % (current,setup.PACKAGE,setup.VERSION)
    
    os.chdir(filename)
    command = "%s setup.py --serenity --virtualenv='%s' install" % (sys.executable,
                                                                    virtualenvname)
    
    os.system(command)
    
    activate = os.path.join(current,LIB)
 
    with open(activate,"w") as fp:
        print >>fp, install_script % (virtualenvname,SOFT,SOFT)
        print >>fp
    
    st = os.stat(activate)
    os.chmod(activate, st.st_mode | stat.S_IEXEC)
    
    shutil.rmtree(os.path.join(virtualenvname,'src'), ignore_errors=True)
    shutil.copytree(filename, os.path.join(virtualenvname,'src'), symlinks=True)
    
    cleanModules()
    

if __name__=="__main__":

    main()
    