#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# 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 Willow Garage, Inc. 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.
#

from __future__ import with_statement

import os
import sys
from subprocess import Popen, PIPE

## Main entrypoint into creating Sphinx documentation
## @return [str]: list of packages that were successfully generated
def generate_sphinx(ctx):
    success = []
    for package, path in ctx.packages.iteritems():
        if package in ctx.doc_packages and ctx.should_document(package) and \
                ctx.has_builder(package, 'sphinx'):
            try:
                
                # currently only allow one sphinx build per package. This
                # is not inherent, it just requires rewriting higher-level
                # logic
                rd_config = [d for d in ctx.rd_configs[package] if d['builder'] == 'sphinx'][0]
            
                # rd_config is currently a flag. In the future, I imagine it pointing
                # to the location of index.rst, among other things

                if os.access(os.path.join(path, "index.rst"), os.R_OK):
                    oldcwd = os.getcwd()
                    os.chdir(path)
                    try:
                        html_dir = os.path.join(oldcwd, ctx.docdir, package, 'html', rd_config.get('output_dir', '.'))
                        command = ['sphinx-build', '-a', '-E', '-b', 'html', '-d', '_build/doctrees', '-D', 'latex_paper_size=letter', '.', html_dir]
                        print "sphinx-building %s [%s]"%(package, ' '.join(command))
                        com = Popen(command, stdout=PIPE).communicate()
                        print 'stdout:'
                        print com[0]
                        print 'stderr'
                        print com[1]
                    finally:
                        # restore cwd
                        os.chdir(oldcwd)
                    success.append(package)
                else:
                    print >> sys.stderr, "ERROR: no index.rst for sphinx build of [%s]"%package
            finally:
                pass
    return success
