# vim: set filetype=python :


import os
import glob

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

try:
    pyenv = env['pyenv'].Clone()
except:
    # scons -c doesn't end up making src_env, so just use regular env.
    pyenv = env.Clone()

pyenv.Append(LIBS=["galsim"])
pyenv['OBJPREFIX'] = '.obj/'

lib_dir = 'lib'
lib_install_dir = os.path.join(env['FINAL_PREFIX'], lib_dir)

# Include the library location within the modules.
# TODO: Check if we still need this, now that we are using LoadableModule
if 'install' in COMMAND_LINE_TARGETS:
    AddRPATH(pyenv,Dir(lib_install_dir).abspath)
else:
    AddRPATH(pyenv,Dir('#lib').abspath)

env1 = pyenv.Clone()

env1.Prepend(CPPPATH=[os.path.join('#include','galsim')])

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

mod_files = []
# This file is typically created by:
# ls *.cpp > files.txt
# in each subdirectory.  But after that, it allows you to remove a file from
# being included in the library by just deleting it from files.txt, rather
# than having to delete the .cpp file.
mod_files.extend(ReadFileList('files.txt'))

# Library file containing generic code
obj_mod = env1.SharedObject(mod_files)

mod = env1.LoadableModule(os.path.join('#galsim','_galsim'), obj_mod,
                          LDMODULEPREFIX='', LDMODULESUFFIX='.so')

mod_targets = [mod]

# NB: With LoadableModule (rather than SharedLibrary), we don't need the RenameLib stuff on Macs.

Default(mod_targets)

if 'install' in COMMAND_LINE_TARGETS:

    installed_mod = env1.Install(dir=python_install_dir, source=mod_targets)
    env1.Alias(target='install', source=installed_mod)
    env['all_builds'] += installed_mod
else:
    env['all_builds'] += mod

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")

    modfiles = [os.path.join(python_install_dir, os.path.basename(str(f[0]))) for f in mod_targets]

    for f in modfiles:
        env1.Alias('uninstall', env1.Command(f, None, deltarget))

# Also load sub-modules:
subdirs = []
for d in subdirs:
    SConscript(os.path.join(d, 'SConscript'), exports='pyenv')

