import os
import glob
import sys

from numscons import GetNumpyEnvironment
from numscons import CheckF77LAPACK
from numscons import write_info
from numscons.core.misc import built_with_mstools, built_with_gnu_f77

env = GetNumpyEnvironment(ARGUMENTS)

#=======================
# Starting Configuration
#=======================
config = env.NumpyConfigure(custom_tests = {'CheckLapack' : CheckF77LAPACK})

#-----------------
# Checking Lapack
#-----------------
st = config.CheckLapack()
if not st:
    raise RuntimeError("no lapack found, necessary for dsolve module")

config.Finish()
write_info(env)

# Build superlu lib
superlu_env = env.Clone()
superlu_def = []
if sys.platform == 'win32':
    superlu_def.append((('NO_TIMER'), 1))
superlu_def.append((('USE_VENDOR_BLAS'), 2))
superlu_env.Append(CPPDEFINES=superlu_def)
superlu_env.Append(CPPPATH=[os.path.join('SuperLU', 'SRC')])

superlu_src = env.Glob(os.path.join('SuperLU', 'SRC', "*.c"))

# XXX: we should detect whether lsame is already defined in BLAS/LAPACK. Here,
# when using MSVC + MKL, lsame is already in MKL
if not (built_with_mstools(env) and (not built_with_gnu_f77(env))):
    superlu_src.append(os.path.join("SuperLU", "SRC", "lsame.c"))
superlu = superlu_env.DistutilsStaticExtLibrary('superlu_src', source=superlu_src)

# Build python extensions
pyenv = env.Clone()
pyenv.Append(CPPPATH=[os.path.join('SuperLU', 'SRC')])
pyenv.Prepend(LIBPATH=["."])
pyenv.Prepend(LIBS=["superlu_src"])
common_src = ['_superlu_utils.c', '_superluobject.c']

pyenv.NumpyPythonExtension('_superlu', source=common_src + ['_superlumodule.c'])
