#!/usr/bin/env python

import os

Import('envGPUampcor')
package = envGPUampcor['PACKAGE']
project = envGPUampcor['PROJECT']
install = envGPUampcor['PRJ_SCONS_INSTALL'] + '/' + package + '/' + project
build = envGPUampcor['PRJ_SCONS_BUILD'] + '/' + package + '/' + project + '/src'

if envGPUampcor['GPU_ACC_ENABLED']:
    envGPUampcor.AppendUnique(CPPPATH=envGPUampcor['CUDACPPPATH'])
    envGPUampcor.AppendUnique(LIBPATH=envGPUampcor['CUDALIBPATH'])
    envGPUampcor.AppendUnique(LIBS=['cuda','cudart'])


###Custom cython builder
cythonBuilder = Builder(action = 'cython3 $SOURCE --cplus',
                        suffix = '.cpp',
                        src_suffix = '.pyx')
envGPUampcor.Append(BUILDERS = {'Pyx2Cpp':cythonBuilder})

def cythonPseudoBuilder(env,source,bld,inst):
    cppCode = env.Pyx2Cpp(source)
    listFiles = [source+'.cpp', 'Ampcor.cpp', 'AmpcorFFT.cpp', 'AmpcorMethods.cpp']
    env.MergeFlags('-fopenmp -O3 -std=c++11 -fPIC -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -Wall -Wstrict-prototypes')

    if (env['GPU_ACC_ENABLED']):
        listFiles.append(os.path.join(build,'gpu-ampcor.o'))
        listFiles.append(os.path.join(build,'gpu-ampcor-linked.o'))
        # Because we build the above CUDA objects by hand, Scons doesn't realize they're shared (usually contained in
        # a separate temporary '.linkinfo' file that's auto-generated by the ObjectEmitter). This is an override just 
        # for this builder to ignore the checks for if gpu-ampcor.o/gpu-ampcor-linked.o are flagged by Scons as shared
        env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
        lib = env.LoadableModule(target = 'GPUampcor.abi3.so', source = listFiles, CPPDEFINES = 'GPU_ACC_ENABLED')
    else:
        lib = env.LoadableModule(target = 'GPUampcor.abi3.so', source = listFiles)
    env.Install(inst,lib)
    env.Alias('install',inst)


envGPUampcor.AddMethod(cythonPseudoBuilder,'Cython')
envGPUampcor.Cython('GPUampcor',build,install)
