Import('env')
Import('create_uninstall_target')
Import('find_sphinx_binary')
Import('installing')

import os
import glob
import subprocess
from functools import partial

SPHINX_BINARY = find_sphinx_binary()


def run_sphinx_binary(builder, **kwargs):
    # SCons passes list of source files but sphinx wants dir name
    source_dir = os.path.dirname(str(kwargs['source'][0]))
    build_dir = os.path.dirname(str(kwargs['target'][0]))
    os.makedirs(build_dir, exist_ok=True)

    command = [SPHINX_BINARY, '-q', '-D', 'man_make_section_directory=0']

    if ARGUMENTS.get('STRICT') == '1':
        command.append('-W')

    subprocess.check_call(command + ['-b', builder, source_dir, build_dir])


# Do not use partial(), but a real function.
# Scons uses this to check if the previous action
# differs from the current action.
# Partial actions are always different.
def run_sphinx_binary_man(**kwargs):
    run_sphinx_binary('man', **kwargs)


if SPHINX_BINARY:
    manpage = env.Command(
        '_build/man/rmlint.1', 'rmlint.1.rst',
        env.Action(run_sphinx_binary_man, "Building manpage from rst...")
    )

    env.Default(manpage)
    env.Alias('man', manpage)

    if installing:
        man_install = env.InstallPerm(
            '$staged_prefix/share/man/man1',
            [manpage],
            0o644,
        )
        env.Alias(['install', 'install-cli'], [manpage, man_install])

    if 'docs' in COMMAND_LINE_TARGETS:
        sources = glob.glob('*.rst')
        sources.remove('rmlint.1.rst')
        targets = ['_build/html/' + os.path.splitext(s)[0] + '.html' for s in sources]
        env.Alias('docs',
            env.Command(
                targets, sources,
                Action(partial(run_sphinx_binary, 'html'), "Building online docs...")
            ),
        )
elif {'man', 'docs'} & set(COMMAND_LINE_TARGETS):
    print('!! sphinx-build not found: cannot build the man/docs targets.')
    Exit(1)


if SPHINX_BINARY and 'uninstall' in COMMAND_LINE_TARGETS:
    create_uninstall_target(env, '$PREFIX/share/man/man1/rmlint.1')
