#!/usr/bin/env python
"""
open/dulcinea/setup.py

Setup script for Dulcinea
"""
Dulcinea_Version = "0.22"

from distutils import core
from distutils.command.build_py import build_py
from distutils.command.sdist import sdist
from glob import glob
import re, sys, os

class DurusWorks_build_py (build_py):

    def find_package_modules(self, package, package_dir):
        self.check_package(package, package_dir)
        module_files = (glob(os.path.join(package_dir, "*.py")) +
                        glob(os.path.join(package_dir, "*.qpy")))
        modules = []
        setup_script = os.path.abspath(self.distribution.script_name)
        for f in module_files:
            abs_f = os.path.abspath(f)
            module = os.path.splitext(os.path.basename(f))[0]
            modules.append((package, module, f))
        return modules

    def build_module(self, module, module_file, package):
        if type(package) is str:
            package = package.split('.')
        elif type(package) not in (list, tuple):
            raise TypeError(
                "'package' must be a string (dot-separated), list, or tuple")
        # Now put the module source file into the "build" area.
        outfile = self.get_module_outfile(self.build_lib, package, module)
        if module_file.endswith(".qpy"):
            outfile = outfile[0:outfile.rfind('.')] + ".qpy"
        dir = os.path.dirname(outfile)
        self.mkpath(dir)
        return self.copy_file(module_file, outfile, preserve_mode=0)

    def byte_compile(self, files):
        try:
            from qpy.compile import compile_qpy_file
        except ImportError:
            build_py.byte_compile(self, files)
        else:
            existing = []
            for file in files:
                if os.path.exists(file):
                    existing.append(file)
                else:
                    alt = file[:-3] + ".qpy"
                    compile_qpy_file(alt)
                    sys.stdout.write('byte-compiling %s\n' % alt)
            build_py.byte_compile(self, existing)

class DurusWorks_sdist (sdist):

    def get_file_list(self):
        sdist.get_file_list(self)
        self.filelist.files = []
        self.filelist.findall()
        print('')
        for name in sorted(self.filelist.allfiles):
            if ".svn" in name:
                continue
            if name.endswith('.pyc'):
                continue
            if name.endswith('.o'):
                continue
            if name.endswith('.so'):
                continue
            if name.endswith('.class'):
                continue
            if name.endswith('~'):
                continue
            if name.endswith('#'):
                continue
            if name.startswith('build/'):
                continue
            if name.startswith('dist/'):
                continue
            self.filelist.files.append(name)
            print('ADDING', name)
        print

    def write_manifest(self):
        pass

if 'sdist' in sys.argv:
    if sys.platform == 'darwin':
        # Omit extended attributes from tarfile
        os.environ['COPYFILE_DISABLE'] = 'true'
    # Make sure that version numbers have all been updated.
    PAT = re.compile(r'\b%s\b' % re.escape(Dulcinea_Version))
    assert len(PAT.findall(open("LICENSE.txt").read())) == 12, Dulcinea_Version
    assert PAT.search(open("CHANGES.txt").readline()), Dulcinea_Version
    assert len(PAT.findall(open("README.txt").read())) == 1, Dulcinea_Version

    # Make sure that copyright statements are current.
    from datetime import datetime
    year = datetime.now().year # no tz, ok
    copyright = "Copyright (c) Corporation for National Research Initiatives %s" % year
    assert open("README.txt").read().count(copyright) == 1

kw = dict(
    name="Dulcinea",
    version=Dulcinea_Version,
    description =("A package of modules useful for developing "
                      "DurusWorks applications."),
    author="CNRI",
    author_email="webmaster@mems-exchange.org",
    url="http://www.mems-exchange.org/software/dulcinea/",
    license="see LICENSE.txt",
    package_dir={'dulcinea':'lib'},
    packages=['dulcinea',
        'dulcinea.property',
        'dulcinea.ui',
        'dulcinea.ui.lib',
        'dulcinea.ui.form',
        'dulcinea.ui.user'],
    scripts=['bin/expire_session.py'],
    cmdclass=dict(
        build_py=DurusWorks_build_py,
        sdist=DurusWorks_sdist)
    )

if hasattr(core, 'setup_keywords'):
    if 'classifiers' in core.setup_keywords:
        kw['classifiers'] = ['Development Status :: 3 - Alpha',
          'Intended Audience :: Developers',
          'Operating System :: Unix',
          'Topic :: Software Development :: Libraries',
          ]
    if 'download_url' in core.setup_keywords:
        kw['download_url'] = ('http://www.mems-exchange.org/software/files'
                              '/dulcinea/Dulcinea-%s.tar.gz' % kw['version'])

core.setup(**kw)
