Import('*')

import sys, os.path, glob
import SCons.Script
import distutils.sysconfig


if env.has_key('enable_python') and env['enable_python'] and 'swig' in env['TOOLS']:
	SWIGScanner = SCons.Scanner.ClassicCPP(
	    "SWIGScan",
	    ".i",
	    "CPPPATH",
	    '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
	)

	env.Append(SCANNERS=[SWIGScanner])
	env.Append(SWIGFLAGS = ['-Werror', '-Wall', '-python', '-modern',
		'-I' + distutils.sysconfig.get_python_inc()])

	# these are the C and python sources generated by swig
	wrap_src = env.CFile(['opensync_wrap.c', 'opensync.py'], 'opensync.i')
	env.Depends(wrap_src, glob.glob('opensync-*.i'))

	# this is the shared library compiled from the C generated by SWIG
	# code using Python's C API doesn't build cleanly with strict aliasing
	wrap_lib = env.SharedLibrary('opensync', 'opensync_wrap.c', SHLIBPREFIX = '_',
		LIBS=['opensync'], LIBPATH='#opensync', CCFLAGS='$CCFLAGS -fno-strict-aliasing')

	# this is a modified version of the python module generated by SWIG
	# we edit the python source to make the opensync.Error class an exception, allowing it to be raised
	# FIXME: find a way (if it exists) of getting SWIG to do this for us
	wrap_mod = env.Command('opensync_hack.py', 'opensync.py',
		'sed "s/^class Error(object):/class Error(Exception):/" $SOURCE > $TARGET')

	env.Install(install_pythonlib, wrap_lib)
	env.InstallAs(os.path.join(install_pythonlib, 'opensync.py'), wrap_mod)
	env.Alias('install', install_prefix)
