# Builds the Boost.Python wrapper under Linux.

import os
import re
import glob

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

boost_cflags=' -ftemplate-depth-100 -DBOOST_PYTHON_DYNAMIC_LIB -fno-inline '

try_dirs = [os.environ.get('BOOST_DIR', '' ),
            '/cvs/boost', '/usr/local/boost',
            '/usr/local/include/boost', '/usr/include/boost',
            '/usr/lib/boost/']
boost_base = ''
for d in try_dirs:
    if os.path.isdir(d):
        boost_base = d
if not boost_base:
    print 'Cannot find Boost directory.'
    print 'Set environment variable: BOOST_DIR'
    sys.exit(1)
    
try_dirs = [os.environ.get('BOOST_LIB_DIR', '' ),
            '/usr/local/lib', '/usr/lib/',
            '/cvs/boost/libs/python/build/bin-stage',
            '/usr/local/boost/libs/python/build/bin-stage'
            ]

boost_lib_dir = ''
for d in try_dirs:
    if os.path.isdir(d):
        boost_lib_dir = d
if not boost_lib_dir:
    print 'Cannot find Boost.Python library.'
    print 'Set environment variable: BOOST_LIB_DIR'
    sys.exit(1)

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

cpppath = ['#/']

libpath = [boost_lib_dir, "/usr/lib/python2.2/config"]

libs = ['boost_python']


# -----------------------------------------------------------
# Pyste scanner
pyste_re = re.compile(r'[\"\'](\w+\.\w+)[\'\"]\)')

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

ccflags = ccflags + boost_cflags

PysteScanner = Scanner(name='PysteScanner', function=pysteScan,
                       argument=None, skeys=['.pyste'])

# Pyste builder.
PysteBuilder = Builder(action="pyste.py $_CPPINCFLAGS --module=${TARGET.base} $SOURCE",
                       suffix='.cpp', src_suffix='.pyste')

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

env.Append(BUILDERS={'PysteBuilder': PysteBuilder},
           SCANNERS=[PysteScanner])



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

srcs = glob.glob("*.pyste")
cpps = []
for src in srcs:
    base = os.path.splitext(src)[0] 
    cpp = base + '.cpp'
    env.PysteBuilder(target=cpp, source=src)
    cpps.append(cpp)
    env.SharedLibrary(base, cpp, LIBS=libs)
