# -*- coding: utf-8 -*-

from setuptools import Command, find_packages, setup
from setuptools.command.egg_info import egg_info

import datetime
import os.path
import logging
import subprocess


README_md = 'README.md'
README_rst = 'README.rst'
VERSION_FILE = 'transmute/_version.py'


# logging.basicConfig(level=logging.DEBUG)

try:
    execfile(VERSION_FILE)
except:
    logging.debug('Failed to read version from %s', VERSION_FILE,
            exc_info=True)
    __version__ = 'unknown'


def read_file(filename):
    try:
        with open(filename) as f:
            return f.read()
    except:
        logging.debug('Failed to read %s', filename, exc_info=True)

def write_file(filename, content):
    with open(filename, 'w') as f:
        return f.write(content)

def execute_command(args, **kwargs):
    # For compatibility with Python 2.6, which doesn't provide
    # subprocess.check_output

    process = subprocess.Popen(args, stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT, **kwargs)

    output, _ = process.communicate()
    exitcode = process.poll()

    if exitcode:
        msg = 'Command %s returned non-zero exit code, %i' % (args, exitcode)
        if output:
            msg += '\nCommand output:\n' + output
        raise Exception(msg)

    return output

class ResetVersion(Command):

    description = "reset package version with version number from git"
    user_options = []

    def initialize_options(self):
        try:
            wd = os.path.dirname(__file__) or None
            revision = execute_command(
                    'git describe --always --dirty=-patched'.split(), cwd=wd)
        except:
            logging.debug('Failed to query git version', exc_info=True)
            return

        # Ensure version is considered final by pip
        revision = revision.rstrip()
        major, sep, rest = revision.partition('-')
        if major.isdigit():
            major += '.0'
        self.distribution.metadata.version = major + sep + rest

    def finalize_options(self):
        pass

    def run(self):
        current_version = self.distribution.metadata.version

        if current_version != __version__:
            version_file_content = '\n'.join([
                "# File generated by %s on %s" % (__file__, datetime.date.today()),
                "__version__ = '%s'" % current_version,
                ""  # End of file line-break
            ])
            write_file(VERSION_FILE, version_file_content)


class EggInfo(egg_info):
    def initialize_options(self):
        egg_info.initialize_options(self)

        # Reset version number before egg_info sets its internal egg_version in
        # finalize_options.
        self.run_command('reset_version')

        # Generate README.rst
        md = read_file(README_md)
        rst = None
        try:
            # Requires pandoc, the tool, and pypandoc, the python module
            import pypandoc

            rst = pypandoc.convert(md, 'rst', format='md')
            write_file(README_rst, rst)
        except:
            logging.debug('Failed to generate %s from %s', README_rst,
                    README_md, exc_info=True)

        self.distribution.metadata.long_description \
                = rst or read_file(README_rst) or md


project_metadata = {
    'name':         'transmute',
    'version':      __version__,
    'author':       'João Abecasis',
    'author_email': 'joao@comoyo.com',
    'url':          'https://github.com/comoyo/python-transmute',
    'description':  'Automatically update Python Eggs on application startup.',
    'classifiers':  [
                        "Programming Language :: Python",
                        "License :: OSI Approved :: Apache Software License",
                        "Operating System :: OS Independent",
                        "Development Status :: 3 - Alpha",
                        "Intended Audience :: Developers",
                        "Topic :: Software Development :: Libraries :: Python Modules",
                        "Topic :: System :: Installation/Setup",
                        "Topic :: System :: Software Distribution",
                    ],
    'packages':     find_packages(exclude=[ 'tests*' ]),
    'cmdclass':     {
                        'egg_info': EggInfo,
                        'reset_version': ResetVersion,
                    },
}
setup(**project_metadata)
