# Builds the SWIG wrappers under Linux.

import os
import re
import glob

# ------------------------------------------------------------
# Configuration
ccflags = "-Wall -O2"
defines = ""
libs = ""

nodep_cpppath = ['/usr/include/python2.2']

cpppath = ['#']

libpath = ['/usr/lib/python2.2/config']

# If scons is given a director[s]=1 argument directors are enabled.
# Also adds a -Wno-unused flag to the compiler.
if ARGUMENTS.get('directors', 0) or ARGUMENTS.get('director', 0):
    defines += " -DDIRECTORS "
    ccflags += " -Wno-unused "

# -----------------------------------------------------------
# SWIG scanner
swig_re = re.compile(r'(?:#include|%include|%import)\s+[\"\'](\w+\.\w+)[\"\']')

def swigScan(node, env, path, arg):
    contents = node.get_contents()
    inc = swig_re.findall(contents)
    srcs = []
    for i in inc:
        f = FindFile(i, cpppath)
        if f:
            srcs.append(f)
    return srcs

SwigScanner = Scanner(name='SwigScanner', function=swigScan,
                      argument=None, skeys=['.i'])

# Pyste builder.
SwigBuilder = Builder(action="swig -c++ -python $_CPPINCFLAGS $DEFINE_FLAGS -o ${TARGET} $SOURCE",
                      suffix='.cxx', src_suffix='.i')

env = Environment(CPPPATH=cpppath,
                  NODEP_CPPPATH=nodep_cpppath, 
                  _NODEP_INCFLAGS='$( ${_concat(INCPREFIX, NODEP_CPPPATH, INCSUFFIX, __env__, RDirs)} $)',
                  CCFLAGS=ccflags + ' $_NODEP_INCFLAGS',
                  DEFINE_FLAGS=defines,
                  SHLIBPREFIX='',
                  LIBPATH=libpath,
                  ENV=os.environ)

# support for other compilers/distcc
if ARGUMENTS.get('CC', 0):
    env.Replace(CC=ARGUMENTS.get('CC'))
if ARGUMENTS.get('CXX', 0):
    env.Replace(CXX=ARGUMENTS.get('CXX'))

env.Append(BUILDERS={'SwigBuilder': SwigBuilder},
           SCANNERS=[SwigScanner])


# ------------------------------------------------------------
# Now specify the sources and build everything.

my_dir = Dir("#").abspath
swig_src = glob.glob(os.path.join(my_dir, "*.i"))

cpp_srcs = []
for src in swig_src:
    base = os.path.splitext(src)[0]
    d = os.path.dirname(base)
    fname = os.path.basename(base)
    modname = '_' + os.path.splitext(fname)[0] + '.so'
    swig_module = os.path.join(d, modname)
    cpp = os.path.join(d, fname + '_wrap.cxx')
    cpp_srcs.append(cpp)
    env.SwigBuilder(target=cpp, source=src)
    env.SharedLibrary(swig_module, cpp, LIBS=libs)
