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

## Copyright (c) 2006, 2007, Joerg Zinke, Jonas Weismueller (team@petunial.com)
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
##
##  * Redistributions of source code must retain the above copyright
##    notice, this list of conditions and the following disclaimer.
##  * Redistributions in binary form must reproduce the above copyright
##    notice, this list of conditions and the following disclaimer in
##    the documentation and/or other materials provided with the
##    distribution.
##  * Neither the name of the Petunial Team nor the names of its
##    contributors may be used to endorse or promote products derived
##    from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
## FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
## COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
## INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
## BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
## LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
## ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
## POSSIBILITY OF SUCH DAMAGE.

"""

latua_documenation

script for generating project documentation

"""

__version__ = "$Revision: 303 $"
# $URL: http://www.petunial.de/svn/latua/tags/0.2/scripts/latua_documentation $

## standard modules
import os
import sys
import optparse
import subprocess

## latua modules
import latua

class _Documentation(latua.Base):
    """Cleanup and propset svn files files."""
    def __init__(self):
        latua.Base.__init__(self)
        self.__system = latua.System()
        self.__version = latua.Version()

    def __docutils(self, path):
        """Find all text files and generate html and pdf."""
        directory = os.path.join(path, "documentation")
        result = self.__system.files.search(directory, "file", ".txt")
        for item in result:
            ## generate html from text
            command = "rst2html --link-stylesheet --stylesheet=documentation.css %s %s.html" % (item, os.path.splitext(item)[0])
            print ">> running: %s" % (command)
            process = subprocess.Popen(command, shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       close_fds=True)
            print process.stdout.read()
            ## generate pdf from text via latex
            command = "rst2latex %s %s.tex" % (item, os.path.splitext(item)[0])
            print ">> running: %s" % (command)
            process = subprocess.Popen(command, shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       close_fds=True)
            print process.stdout.read()
            command = "pdflatex -output-directory %s %s.tex" % (directory, os.path.splitext(item)[0])
            print ">> running: %s" % (command)
            process = subprocess.Popen(command, shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       close_fds=True)
            print process.stdout.read()

    def __epydoc(self, path, application):
        """Generate api documentation from source."""
        directory = os.path.join(path, "documentation", "api")
        if not os.path.isdir(directory):
            os.makedirs(directory)
        ## generate html from source
        command = "epydoc --html -v --name=%s --docformat=plaintext --show-imports --graph=all --show-sourcecode -o %s %s" % (application, directory, os.path.join(path, application))
        print ">> running: %s" % (command)
        process = subprocess.Popen(command, shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   close_fds=True)
        print process.stdout.read()
        ## generate pdf from source
        command = "epydoc --pdf -v --name=%s --docformat=plaintext --show-imports --graph=all --show-sourcecode -o %s %s" % (application, directory, os.path.join(path, application))
        print ">> running: %s" % (command)
        process = subprocess.Popen(command, shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   close_fds=True)
        print process.stdout.read()

    def __cleanup(self, path):
        """Cleanup temorary files."""
        directory = os.path.join(path, "documentation")
        files = self.__system.files.search(directory, "file", ".aux")
        print ">> removing .aux files:"
        for item in files:
            print ">> %s" % (item)
            os.remove(item)
        files = self.__system.files.search(directory, "file", ".log")
        print ">> removing .log files:"
        for item in files:
            print ">> %s" % (item)
            os.remove(item)
        files = self.__system.files.search(directory, "file", ".out")
        print ">> removing .out files:"
        for item in files:
            print ">> %s" % (item)
            os.remove(item)
        files = self.__system.files.search(directory, "file", ".tex")
        print ">> removing .tex files:"
        for item in files:
            print ">> %s" % (item)
            os.remove(item)

    def run(self):
        """Main function."""
        ## create an command line option parser
        options_parser = optparse.OptionParser(usage="%prog [options] application path",
                                               version="latua_documentation latua v%s\n%s" %
                                               (self.__version.latua_version,
                                                self.__version.copyright))
        (options, arguments) = options_parser.parse_args()
        ## check given arguments
        if not len(arguments) == 2:
            options_parser.error("incorrect number of arguments")
        application = arguments[0]
        path = arguments[1]
        ## docutils documentation
        self.__docutils(path)
        ## epydoc documentation
        self.__epydoc(path, application)
        ## cleanup temporary files
        self.__cleanup(path)

## last line but first step
if __name__ == "__main__":
    _documentation = _Documentation()
    _documentation.run()

