sphinx = find_program('sphinx-build', required: true)
doxygen = find_program('doxygen', required: true)
breathe = find_program('breathe-apidoc', required: true)

sphinx_c = run_command(sphinx, '--version')
breathe_c = run_command(breathe, '--version')
doxygen_c = run_command(doxygen, '--version')

sphinx_v = sphinx_c.stdout().split(' ')[1].strip()
breathe_v = breathe_c.stdout().split(' ')[2].strip()
doxygen_v = doxygen_c.stdout().strip()

if sphinx_v.version_compare('< 2.1.0')
	error('Use at least sphinx version 2.1.0, found ' + sphinx_v)
endif

if breathe_v.version_compare('< 4.11')
	error('Use at least breathe version 4.11, found ' + breathe_v)
endif

if doxygen_v.version_compare('< 1.8')
	error('Use at least doxygen version 1.8, found ' + doxygen_v)
endif

doxygen_database = meson.current_build_dir() + '/doxygen_doc'

# modify the sphinx configuration and the breathe doxygen XML database
# to point where its being generated by doxygen
sphinx_conf_data = configuration_data()
sphinx_conf_data.set('BUILD_ROOT', doxygen_database)
sphinx_conf_data.set('VERSION', meson.project_version())
sphinx_conf = configure_file(
		input: 'conf.py.in',
		output: 'conf.py',
		configuration: sphinx_conf_data
)

doxy_conf_data = configuration_data()
doxy_conf_data.set('SRC_ROOT', meson.source_root())
doxy_conf_data.set('OUTPUT_DIR', doxygen_database)
doxygen_conf_weston = configure_file(
		input: 'doxygen.ini.in',
		output: 'doxygen.ini',
		configuration: doxy_conf_data
)

script_data = configuration_data()
script_data.set('SRCDIR', meson.current_build_dir())
script_data.set('OUTDIR', meson.current_build_dir() + '/doc')
script_data.set('DOXYGEN_CONF', meson.current_build_dir() + '/doxygen.ini')
script_data.set('DOXYGEN_CMD', doxygen.path())
script_data.set('SPHINX_CMD', sphinx.path())
script_doxy_sphinx = configure_file(
	input: 'run_doxygen_sphinx.sh.in',
	output: 'run_doxygen_sphinx.sh',
	configuration: script_data
)

# copy everything to build_dir, if you plan on adding other files in the top
# rootdir of sourcedir, please add them here as well, otherwise use 'toc/'s
# meson.build file
sphinx_files = ['index.rst']
foreach file : sphinx_files
	configure_file(input: file, output: file, copy: true)
endforeach

# and those in toc
subdir('toc')

sphinx_doc = custom_target(
		'weston-doc-breathe',
		command: script_doxy_sphinx,
		output: 'doc',
		build_by_default: true,
)

# we need this because we will have a stale 'doc' directory
# and this forces it to be rebuilt
docs = run_target(
		'docs',
		command: script_doxy_sphinx,
)

install_subdir(
	sphinx_doc.full_path(),
	install_dir: join_paths(dir_data, 'doc', 'weston'),
	strip_directory: true,
)