"""
$URL: svn+ssh://sting.mems-exchange.org/repos/trunk/DurusWorks/setup.py $
$Id: setup.py 34060 2011-07-01 11:37:25Z dbinger $

This is the setup.py file for DurusWorks.
"""
DurusWorks_Version = "1.0"

import re, sys, os
assert sys.version >= "2.4"

from glob import glob
from distutils.core import setup
from distutils.command.build_ext import build_ext
from distutils.command.build_py import build_py
from distutils.command.sdist import sdist
from distutils.extension import Extension

if 'sdist' in sys.argv:
    if sys.platform == 'darwin':
        # Omit extended attributes from tarfile
        os.environ['COPYFILE_DISABLE'] = 'true'

    # Make sure that copyright statements are current.
    from datetime import datetime
    year = datetime.now().year
    copyright = \
        "Copyright (c) %s Corporation for National Research Initiatives" % year
    assert open("README.txt").read().count(copyright) == 1, repr(copyright)
    assert open("durus/__init__.py").read().count(copyright) == 1, repr(copyright)
    assert open("sancho/__init__.py").read().count(copyright) == 1, repr(copyright)
    assert open("qp/__init__.py").read().count(copyright) == 1, repr(copyright)
    assert open("qpy/__init__.py").read().count(copyright) == 1, repr(copyright)


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


class DurusWorks_build_ext (build_ext):

    def run(self):
        self.force = True # Always rebuild.
        self.inplace = True # Always build in place.
        build_ext.run(self)

persistent = Extension(name="durus._persistent", sources=["durus/_persistent.c"])
quoted = Extension(name="qpy.quoted", sources=["qpy/quoted.c"])
passfd = Extension(name="qp.hub.passfd", sources=['qp/hub/passfd.c'])

setup(
    name = "DurusWorks",
    version = "1.0",
    description = "A Web Application Framework Using Durus",
    long_description = """
    A small and powerful web application framwork that includes a
    transactional object database,
    a flexible http or scgi deployment system,
    multiple-site management tools,
    a way of specifying and checking attribute types,
    user and session management,
    a form framework,
    a unit testing system,
    a script for identifying unused imports and unknown names,
    and programmer-oriented
    package for generating safely quoted html.
    """,
    scripts = [
        "durus/durus",
        "qp/bin/qp", "qp/bin/qpcensus.py",
        "qpy/qpcheck.py", "qpy/qpyrun.py",
        "sancho/urun.py"],
    packages = [
        "durus", "durus.test",
        "qpy", "qpy.test", "qpy.example",
        "qp",
        "qp.http", "qp.http.test",
        "qp.hub", "qp.hub.test",
        "qp.pub", "qp.pub.test",
        "qp.fill", "qp.fill.test",
        "qp.lib", "qp.lib.test",
        "qp.mail", "qp.mail.test",
        "qp.sites",
        "sancho", "sancho.test"
        ],
    platforms = ['Python 2.4 - 3.2 on posix or darwin'],
    author = "CNRI",
    author_email = "webmaster@mems-exchange.org",
    url = "http://www.mems-exchange.org/software/DurusWorks/",
    ext_modules = [persistent, quoted, passfd],
    cmdclass=dict(
        build_py=DurusWorks_build_py,
        build_ext=DurusWorks_build_ext,
        sdist=DurusWorks_sdist),
    license = "see LICENSE.txt",
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: DurusWorks',
        'Intended Audience :: Developers',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: POSIX',
        'Operating System :: Unix',
        'Programming Language :: Python :: 2.4',
        'Programming Language :: Python :: 2.5',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.0',
        'Programming Language :: Python :: 3.1',
        'Programming Language :: Python :: 3.2',
        'Topic :: Database',
        'Topic :: Database :: Database Engines/Servers',
        'Topic :: Database :: Front-Ends',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP :: HTTP Servers',
        'Topic :: Internet :: WWW/HTTP :: Site Management',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Widget Sets',
        'Topic :: Text Processing :: Markup :: HTML',
        'Topic :: Text Processing :: Markup :: XML',
        ]
      )
