# vim: set filetype=python :

import os
import sys
import glob

Import('env')
ReadFileList=env['_ReadFileList']

python_dir = 'galsim'
python_install_dir = os.path.join(env['PYPREFIX'], python_dir)

py_files = glob.glob("*.py")

subdir_list = [ 'config', 'des', 'deprecated' ]

py_files_sub = []
python_install_subdir = []
for subdir in subdir_list:
    py_files_sub.append(glob.glob(os.path.join(subdir,"*.py")))
    python_install_subdir.append(os.path.join(python_install_dir,subdir))

# If the python_install_dir being used isn't in the sys.path, then warn the user
# that they should add that path to their PYTHONPATH environment variable.
def CheckPyPrefix(target, source, env):
    import subprocess

    # Get sys.path for the intended python version.
    python = env['PYTHON']
    cmd = "%s -c \"import sys; print sys.path\""%python
    p = subprocess.Popen([cmd],stdout=subprocess.PIPE,shell=True)
    sys_path = p.stdout.read().strip()
    sys_path = eval(sys_path)

    # Convert everything to an abspath to make sure everyone is using the same notation.
    pyprefix = os.path.abspath(env['PYPREFIX'])
    real_pyprefix = os.path.realpath(pyprefix)
    sys_path = [ os.path.realpath(os.path.abspath(d)) for d in sys_path ]

    # If installing into a staging area, try stripping off an initial INSTALL_PREFIX
    # from pyprefix and put on FINAL_PREFIX instead.
    if ( real_pyprefix not in sys_path and 
         env['FINAL_PREFIX'] != env['INSTALL_PREFIX'] and 
         pyprefix.startswith(env['INSTALL_PREFIX']) ):
        pyprefix = pyprefix.replace(env['INSTALL_PREFIX'],env['FINAL_PREFIX'],1)
        real_pyprefix = os.path.realpath(pyprefix)
        
    if real_pyprefix not in sys_path:
        env['final_messages'].append("""
WARNING: The python installation prefix: %s
         is not in the search path for %s.

         You should add this directory to your PYTHONPATH environment
         variable so python will find the installed galsim modules.

         For example, if you use bash, you should add the line:
             export PYTHONPATH=$PYTHONPATH:%s
         to your .bashrc or .bash_profile file.
"""%(pyprefix,python,pyprefix))


env['BUILDERS']['CheckPyPrefix'] = Builder(action = CheckPyPrefix)

# Special -- we used to have a file io.py in the galsim directory that clashed with 
# the regular io module when doing `import io` within one of these files.
# This file is now called catalog.py, which is a better name anyway, but we just make 
# sure that the old io.py or io.pyc isn't still lingering and causing trouble.
io_files = [ 'io.py', 'io.pyc' ]
for f in io_files:
    # Delete it here
    if os.path.isfile(f): os.remove(f)
    # And also in the install directory
    installed_f = os.path.join(python_install_dir, f)
    try:
        if os.path.isfile(installed_f): os.remove(installed_f)
    except:
        # Might not have permission without sudo, so ignore errors that might happen here.
        # It will get done when the user runs `sudo scons install`
        pass

if 'install' in COMMAND_LINE_TARGETS:

    installed_py = env.Install(dir=python_install_dir, source=py_files)

    for i in range(len(subdir_list)):
        installed_py += env.Install(dir=python_install_subdir[i], source=py_files_sub[i])

    env.Alias(target='install', source=installed_py)
    env['all_builds'] += installed_py

    check = env.CheckPyPrefix(target='#/check', source=None)
    Depends(check,[installed_py, '#pysrc', '#bin', python_install_dir])
    AlwaysBuild(check)
    env.Alias(target='install', source=check)
    env['all_builds'] += check


if 'uninstall' in COMMAND_LINE_TARGETS:
    # There is no env.Uninstall method, we must build our own
    # MJ: The scons delete function doesn't actually delete directories a la rm -rf
    # I think this is a feature they will add someday, so maybe not worth worrying about it.
    # but if we really want the galsim directory to be deleted on an uninstall, we
    # should change this.  Proabaly roll our own Delete function.
    deltarget = Delete("$TARGET")

    for f in py_files:
        env.Alias('uninstall', env.Command(os.path.join(python_install_dir, f), None, deltarget))

    for i in range(len(subdir_list)):
        for f in py_files_sub[i]:
            env.Alias('uninstall', env.Command(os.path.join(python_install_subdir[i], f), 
                      None, deltarget))

