#!/usr/bin/env python

"""
setup.py file for the libbuffy python bindings
"""

from distutils.core import setup, Extension
import distutils.command.build
import subprocess

# Code taken from http://code.activestate.com/recipes/502261-python-distutils-pkg-config/
# and then kind of fixed so that at least it is not offensive.
# It is however offensive that distutils doesn't do something as common as
# pkg-config by default. But then again, distutils is, as a whole, offensive.
def pkgconfig(*packages, **kw):
    flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}

    # Invoke pkg-config
    proc = subprocess.Popen(("pkg-config", "--libs", "--cflags") + packages,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate()
    if proc.returncode != 0:
        raise RuntimeError("pkg-config returned error %d: %s" % (proc.returncode, err.strip()))

    # Enrich args with pkg-config output
    for token in out.split():
        arg = flag_map.get(token[:2], "extra_link_args")
        kw.setdefault(arg, []).append(token[2:])

    return kw

buffy_module = Extension('_Buffy', ['buffy.i'],
                         **pkgconfig('libbuffy >= 1.4', swig_opts=['-c++', '-I/usr/include'])
                        )

# distutils pretends it supports swig, but it obviously does it wrong (it is
# after all, as mentioned above, offensive). In this case, it looks for the
# swig-generated .py file before it runs swig to generate it. Doh!
#
# We therefore kick it by running build_ext first, so that Buffy.py is
# generated before build_py wants it.
#
# (sort is guaranteed stable since python 2.4, so we can depend on it)
distutils.command.build.build.sub_commands.sort(key=lambda x:x[0] != "build_ext")

setup(name = 'Buffy',
       version = '0.16',
       author      = "Enrico Zini <enrico@enricozini.org>",
       description = "libbuffy bindings for Python",
       ext_modules = [buffy_module],
       py_modules = ["Buffy"],
       )
