#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from setuptools import setup, Extension

build = 'build'
srcdir = '@srcdir@'
top_builddir = '@top_builddir@'
top_srcdir = '@top_srcdir@'
libintl = '@LIBINTL@'
libiconv = '@LIBICONV@'
extra_libs = []
extra_libs.extend(libintl.split())
extra_libs.extend(libiconv.split())

# FIXME: On Mingw, Cython seems to call gcc in such a way that it doesn't understand UNIX paths
if os.name == 'nt':
    for i in range(len(extra_libs)):
        if extra_libs[i][0] == '/':
            extra_libs[i] = os.popen('cygpath --windows ' + extra_libs[i]).read().rstrip()

try:

    if srcdir != '.':
        with open(os.path.join(srcdir, 'Recode.c')) as f:
            buffer = f.read()
        with open('Recode.c', 'w') as f:
            f.write(buffer)

    setup(ext_modules=[
        Extension('Recode', ['Recode.c'],
                  include_dirs=[top_builddir, os.path.join(top_srcdir, 'src'),
                                os.path.join(top_srcdir, 'lib'),
                                os.path.join(top_builddir, 'lib')],
                  library_dirs=[os.path.join(top_builddir, 'src', '.libs'),
                                os.path.join(top_builddir, 'lib', '.libs')],
                  libraries=['recode', 'gnu'],
                  extra_link_args=extra_libs)
        ])

finally:

    if srcdir != '.':
        if os.path.exists('Recode.c'):
            os.remove('Recode.c')
