# SPDX-FileCopyrightText: Copyright The SCons Foundation (https://scons.org)
# SPDX-License-Identifier: MIT

"""
SConstruct file for building SCons manpages.

This is usually invoked as a separate build by the top-level SCons build.

If invoked directly, can add SKIP_PDF=1 to avoid pdf and epub generation.
"""

import os

env = Environment(
    ENV={'PATH': os.environ['PATH']},
    tools=['docbook', 'gs', 'zip'],
    toolpath=['../../SCons/Tool'],
    DOCBOOK_DEFAULT_XSL_HTML='html.xsl',
    DOCBOOK_DEFAULT_XSL_PDF='pdf.xsl',
)

skip_pdf = ARGUMENTS.get('SKIP_PDF', False)
has_pdf = False
if not skip_pdf and any((env.WhereIs('fop'), env.WhereIs('xep'))):
    has_pdf = True

# Helper function, combining all the steps for a single target
def createManPages(env, target):
    env.DocbookXInclude('%s_xi.xml' % target, '%s.xml' % target)
    env.DocbookXslt(
        '%s_db.xml' % target, '%s_xi.xml' % target, xsl='../xslt/to_docbook.xslt'
    )
    env.DocbookHtml('scons-%s.html' % target, '%s_db.xml' % target)
    env.DocbookMan('%s.1' % target, '%s_db.xml' % target)
    if has_pdf:
        env.DocbookPdf('scons-%s.pdf' % target, '%s_db.xml' % target)


#
# Create MAN pages
#
createManPages(env, "scons")
createManPages(env, "sconsign")
createManPages(env, "scons-time")

has_gs = False
if env.WhereIs('gs'):
    has_gs = True

#
# Create the EPUB format
#
if has_gs and has_pdf:
    jpg = env.Gs(
        'OEBPS/cover.jpg',
        'scons-scons.pdf',
        GSFLAGS='-dNOPAUSE -dBATCH -sDEVICE=jpeg -dFirstPage=1 -dLastPage=1 -dJPEGQ=100 -r72x72 -q',
    )
    epub = env.DocbookEpub('scons-man.epub', 'scons_db.xml', xsl='epub.xsl')
    env.Depends(epub, jpg)
