import os

from distribute_setup import use_setuptools
use_setuptools()

from setuptools import setup

ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR, 'ldt')

version_variables = {}
try:
    execfile(os.path.join(SOURCE_DIR, "__init__.py"), version_variables)
except:
    pass

version = version_variables['__version__']

def fullsplit(path, result=None):
    """
    Split a pathname into components (the opposite of os.path.join) in a
    platform-neutral way.
    """
    if result is None:
        result = []
    head, tail = os.path.split(path)
    if head == '':
        return [tail] + result
    if head == path:
        return result
    return fullsplit(head, [tail] + result)

packages, data_files, path_processed = [], {}, []

#TODO : uses find_packages form setuptools and teh mercurial extension

for dirpath, dirnames, filenames in os.walk(SOURCE_DIR, True):
    # Ignore dirnames that start with '.'
    if dirpath in path_processed:
        continue
    path_processed.append(dirpath)
    for i, dirname in enumerate(dirnames):
        if dirname.startswith('.'): del dirnames[i]
    if '__init__.py' in filenames:
        packages.append('.'.join(fullsplit(dirpath)))
    else:
        new_data_files = []
        base_path_list = fullsplit(dirpath)[:-1]
        base_path = "/".join(base_path_list) + "/"
        key = '.'.join(base_path_list)
        for ldirpath, ldirnames, lfilenames in os.walk(dirpath):
            path_processed.append(ldirpath)
            new_data_files.extend([os.path.join(ldirpath[len(base_path):], f) for f in lfilenames])
        data_files.setdefault(key, []).extend(new_data_files)

#write MANIFEST.in

m = open("MANIFEST.in", "w")

m.write("exclude MANIFEST.in\n")
for key, file_list in data_files.iteritems():
    for filename in file_list:
        m.write("include %s/%s\n" % (key.replace(".", "/"), filename))
m.close()

setup(
    name='ldt',
    version=version,
    author='Yves-Marie Haussonne (IRI)',
    author_email='contact@iri.centrepompidou.fr',
    packages=packages,
    package_data=data_files,
    scripts=[],
    url='https://www.iri.centrepompidou.fr/dev/hg/platform',
    license='LICENSE.txt',
    description='Platform ldt',
    long_description=open('README.txt').read(),
    zip_safe=False,
    classifiers=['Development Status :: 5 - Production/Stable',
                   'Environment :: Web Environment',
                   'Framework :: Django',
                   'Intended Audience :: Developers',
                   'License :: Ceccil-C',
                   'Operating System :: OS Independent',
                   'Programming Language :: Python',
                   'Topic :: Utilities'],
)
