import glob
import os
from subprocess import Popen, PIPE
from distutils import sysconfig

Import('env')

def call(cmd, silent=True):
    stdin, stderr = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
    if not stderr:
        return stdin.strip()
    elif not silent:
        print stderr


prefix = env['PREFIX']
target_path = os.path.normpath(sysconfig.get_python_lib() + os.path.sep + env['MAPNIK_NAME'])

py_env = env.Clone()

py_env.Append(CPPPATH = sysconfig.get_python_inc())

py_env.Append(CPPDEFINES = env['LIBMAPNIK_DEFINES'])

py_env['LIBS'] = [env['MAPNIK_NAME'],'libboost_python']

link_all_libs = env['LINKING'] == 'static' or env['RUNTIME_LINK'] == 'static'

# even though boost_thread is no longer used in mapnik core
# we need to link in for boost_python to avoid missing symbol: _ZN5boost6detail12get_tss_dataEPKv / boost::detail::get_tss_data
py_env.AppendUnique(LIBS = 'boost_thread%s' % env['BOOST_APPEND'])

if link_all_libs:
    py_env.AppendUnique(LIBS=env['LIBMAPNIK_LIBS'])

# note: on linux -lrt must be linked after thread to avoid: undefined symbol: clock_gettime
if env['RUNTIME_LINK'] == 'static' and env['PLATFORM'] == 'Linux':
    py_env.AppendUnique(LIBS='rt')

# TODO - do solaris/fedora need direct linking too?
if env['PLATFORM'] == 'Darwin':
    python_link_flag = '-undefined dynamic_lookup'

paths = '''
"""Configuration paths of Mapnik fonts and input plugins (auto-generated by SCons)."""

from os.path import normpath,join,dirname

mapniklibpath = '%s'
mapniklibpath = normpath(join(dirname(__file__),mapniklibpath))
'''

paths += "inputpluginspath = join(mapniklibpath,'input')\n"

if env['SYSTEM_FONTS']:
    paths += "fontscollectionpath = normpath('%s')\n" % env['SYSTEM_FONTS']
else:
    paths += "fontscollectionpath = join(mapniklibpath,'fonts')\n"

paths += "__all__ = [mapniklibpath,inputpluginspath,fontscollectionpath]\n"

if not os.path.exists(env['MAPNIK_NAME']):
    os.mkdir(env['MAPNIK_NAME'])

file('mapnik/paths.py','w').write(paths % (env['MAPNIK_LIB_DIR']))

# force open perms temporarily so that `sudo scons install`
# does not later break simple non-install non-sudo rebuild
try:
    os.chmod('mapnik/paths.py',0666)
except: pass

# install the shared object beside the module directory
sources = glob.glob('src/*.cpp')

if 'install' in COMMAND_LINE_TARGETS:
    # install the core mapnik python files, including '__init__.py'
    init_files = glob.glob('mapnik/*.py')
    if 'mapnik/paths.py' in init_files:
        init_files.remove('mapnik/paths.py')
    init_module = env.Install(target_path, init_files)
    env.Alias(target='install', source=init_module)
    # fix perms and install the custom generated 'paths.py'
    targetp = os.path.join(target_path,'paths.py')
    env.Alias("install", targetp)
    # use env.Command rather than env.Install
    # to enable setting proper perms on `paths.py`
    env.Command( targetp, 'mapnik/paths.py',
        [
        Copy("$TARGET","$SOURCE"),
        Chmod("$TARGET", 0644),
        ])

if 'uninstall' not in COMMAND_LINE_TARGETS:
    if env['HAS_CAIRO']:
        py_env.Append(CPPPATH = env['CAIRO_CPPPATHS'])
        py_env.Append(CPPDEFINES = '-DHAVE_CAIRO')
        if link_all_libs:
            py_env.Append(LIBS=env['CAIRO_ALL_LIBS'])

    if env['HAS_PYCAIRO']:
        py_env.Append(CPPDEFINES = '-DHAVE_PYCAIRO')
        py_env.Append(CPPPATH = env['PYCAIRO_PATHS'])

py_env.Append(LINKFLAGS=python_link_flag)
py_env.AppendUnique(LIBS='mapnik-json')
py_env.AppendUnique(LIBS='mapnik-wkt')

_mapnik = py_env.LoadableModule('mapnik/_mapnik', sources, LDMODULEPREFIX='', LDMODULESUFFIX='.so')

Depends(_mapnik, env.subst('../../src/%s' % env['MAPNIK_LIB_NAME']))
Depends(_mapnik, env.subst('../../src/json/libmapnik-json${LIBSUFFIX}'))
Depends(_mapnik, env.subst('../../src/wkt/libmapnik-wkt${LIBSUFFIX}'))

if 'uninstall' not in COMMAND_LINE_TARGETS:
    pymapniklib = env.Install(target_path,_mapnik)
    py_env.Alias(target='install',source=pymapniklib)

env['create_uninstall_target'](env, target_path)

@@ -1258,16 +1258,38 @@
 ng too?%0A
+python_link_flag = ''%0A
 if env%5B'

fix build on linux