# This file performs the installation step once the build is complete.
# Installation primarily involves copying the build results to the
# IronPython site-packages directory.

import os
import sys
import shutil
import tempfile
from os.path import dirname, isdir, isfile, join

src_dir = join(os.getcwd(), "scipy")

def install():
    print "INSTALLING ..."
    sp_dir = join(sys.prefix, r'Lib\site-packages')
    dll_dir = join(sys.prefix, 'DLLs')
    if not isdir(dll_dir):
        os.mkdir(dll_dir)

    ignore_pys = ["setup.py", "iron_install.py"]
    ignore_libs = ["Microsoft.Scripting.dll",
                   "Microsoft.Scripting.Metadata.dll",
                   "Microsoft.Dynamic.dll",
                   "IronPython.dll",
                   "IronPython.Modules.dll",
                   "NumpyDotNet.dll",
                   "NpyAccessLib.dll",
                   "ndarray.dll"]

    vs_dir = None
    ifort_dir = None
    
    if os.environ.has_key("VSINSTALLDIR"):
        vs_dir = os.environ["VSINSTALLDIR"]
    elif os.environ.has_key("ProgramFiles(x86)"):
        vs_dir = join(os.environ["ProgramFiles(x86)"], "Microsoft Visual Studio 10.0")
    elif os.environ.has_key("ProgramFiles"):
        vs_dir = join(os.environ["ProgramFiles"], "Microsoft Visual Studio 10.0")
    
    if vs_dir is None or not os.path.exists(vs_dir):
        print "Unable to determine Visual Studio installation directory."
        exit(1)

    if os.environ.has_key("IFORTINSTALLDIR"):
        ifort_dir = os.environ.has_key("IFORTINSTALLDIR")
    else:
        ifort_dir = join(vs_dir, "../Intel/ComposeXE-2011")
        if not os.path.exists(ifort_dir):
            pf = os.environ["ProgramFiles(x86)"] if os.environ.has_key("ProgramFiles(x86)") else os.environ["ProgramFiles"]
            ifort_dir = join(pf, "Intel/ComposerXE-2011")

    if not os.path.exists(ifort_dir):
        print "Unable to determine Intel Fortran Composer installation directory."
        exit(1)

    # Finally we can setup the debug and release libraries we need to copy in.
    redist_dir = join(ifort_dir, "redist/ia32/compiler")
    debug_libs = [join(redist_dir, "libmmd.dll"),
                  join(redist_dir, "libmmdd.dll"),
                  join(redist_dir, "libiomp5md.dll"),
                  join(redist_dir, "libifcoremd.dll"),
                  join(redist_dir, "libifcoremdd.dll")]
    
    release_libs = []

    # Recursively walk the directory tree and copy all .py files into the
    # site-packages directory and all .dll files into DLLs.
    for root, dirs, files in os.walk("."):
        for fn in files:
            rel_path = join(root, fn)
            if fn.endswith('.py') and fn not in ignore_pys or fn.endswith('.npz'):
                dst_dir = dirname(join(sp_dir, rel_path))
                if not isdir(dst_dir):
                     os.makedirs(dst_dir)

                # Rename the _clr.py files to remove the _clr suffix.
                # Only used for IronPython.
                if fn.endswith('_clr.py'):
                    dst_file = join(dst_dir, fn[:-7] + ".py")
                else:
                    dst_file = join(dst_dir, fn)

                #print "Copy %s to %s" % (rel_path, dst_file)
                shutil.copy(rel_path, dst_file)
            elif fn.endswith('.dll') and fn not in ignore_libs:
                dst_file = join(dll_dir, fn)
                if isfile(dst_file):
                    # Rename existing file because it is probably in use
                    # by the ipy command.
                    tmp_dir = tempfile.mkdtemp()
                    os.rename(dst_file, join(tmp_dir, fn))
                #print "Copy %s to %s" % (rel_path, dst_file)
                shutil.copy(rel_path, dst_file)

    libs_to_copy = release_libs if release else debug_libs
    for lib in libs_to_copy:
        dest = join(dll_dir, os.path.basename(lib))
        if not os.path.exists(dest):
            #print "Copying %s" % lib
            shutil.copy(lib, dest)
        else:
            #print "%s already exists" % dest
            pass

    write_config(join(sp_dir, r'scipy\__config__.py'))
    write_version(join(sp_dir, r'scipy\version.py'))


def write_config(path):
    fo = open(path, 'w')
    fo.write("""# this file is generated by ironsetup.py
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]

umfpack_info={}
lapack_opt_info={'extra_link_args': []}
blas_opt_info={'extra_link_args': []}

def get_info(name):
    g = globals()
    return g.get(name, g.get(name + "_info", {}))

def show():
    for name,info_dict in globals().items():
        if name[0] == "_" or type(info_dict) is not type({}): continue
        print(name + ":")
        if not info_dict:
            print("  NOT AVAILABLE")
        for k,v in info_dict.items():
            v = str(v)
            if k == "sources" and len(v) > 200:
                v = v[:60] + " ...\\n... " + v[-60:]
            print("    %s = %s" % (k,v))
""")
    fo.close()


def write_version(path):
    fo = open(path, 'w')
    fo.write("""# this file is generated by ironsetup.py
version = '0.7.0'
release = %s

if not release:
    version += ".dev"
""" % release)
    fo.close()


if __name__ == '__main__':
    if "--debug" in sys.argv:
        release = False
    elif "--release" in sys.argv:
        release = True
    else:
        print "Please specify the build type, either --debug or --release"
        exit()
		
    install()
