# waf script called from the root wscript, by
# conf.recurse("help")

# Mallard waf adaptor written by Ulrik Sverdrup
# may be distributed, changed, used, etc freely for any purpose

## Mallard functionality definitions ##
import os
from waflib import Logs, TaskGen

def _read_makefile_am(filename):
	"read a Makefile.am file for HELP_* variable definitions, return a dict"
	varstring = open(filename).read()
	varstring = varstring.replace("\\\n", " ")
	varlines = [L for L in varstring.splitlines() if L.startswith("HELP")]
	return dict(tuple(map(str.strip, var.split("=", 1))) for var in varlines)

def init_mallard(self):
	mf_am = self.path.find_resource(self.variable_definitions)
	HELP_VAR = _read_makefile_am(mf_am.abspath())

	require_vars = "HELP_ID HELP_LINGUAS HELP_FILES".split()
	have_vars = set(var for var in HELP_VAR if HELP_VAR[var])
	missing_vars = set(require_vars).difference(have_vars)
	if missing_vars:
		print("Missing HELP variable declarations in {}:".format(mf_am.abspath()))
		print("\n".join(missing_vars))

	self.bld.env.update(HELP_VAR)
	self.default_install_path='${PREFIX}/share/help'

def apply_mallard(self):
	bld = self.bld
	lst = self.to_list(bld.env["HELP_LINGUAS"])
	cnode = self.path.find_dir("C")

	pages = [p.name for p in cnode.ant_glob(["*.page", "*.xml"])]

	# Check if the declared page list is consistent
	declared_pages = self.to_list(bld.env["HELP_FILES"])
	missing_pages = set(pages).difference(declared_pages)
	if missing_pages:
		print("Warning: Some pages not declared:")
		print("\n".join(missing_pages))

	install_path = lambda lang: os.path.join(bld.env.DATADIR, "help", lang, "${HELP_ID}")

	for lang in lst:
		node = self.path.find_resource("%s/%s.po" % (lang, lang))
		mo = self.path.find_or_declare("%s/%s.mo" % (lang, lang))
		bld(name='msgfmt', color='BLUE',
		    rule='${MSGFMT} ${SRC} -o ${TGT}',
		    source=node,
		    target=mo,
		    )
		for page in pages:
			out = self.path.find_or_declare('%s/%s' % (lang, page))
			src = self.path.find_resource('C/%s' % page)
			bld(name='itstool', color='BLUE',
			    rule='${ITSTOOL} -m ${SRC} -o ${TGT}',
			    source=[mo, src],
			    target=out,
			    install_path=install_path(lang)
			    )

	if bld.is_install:
		page_nodes = [cnode.find_resource(page) for page in pages]
		instdir = install_path("C")
		bld.install_files(instdir, page_nodes)


TaskGen.feature("mallard")(init_mallard)
TaskGen.feature("mallard")(apply_mallard)
TaskGen.after('init_mallard')(apply_mallard)

## End Mallard functionality ##


# Build Configuration


def configure(ctx):
	lookfor = "itstool"
	try:
		ctx.find_program('msgfmt', var='MSGFMT')
		ctx.find_program(lookfor, var='ITSTOOL')
		ctx.env.docs = True
	except ctx.errors.ConfigurationError:
		Logs.warn("'{}' not found; documentation build disabled".format(lookfor))
		ctx.env.docs = False

def build(ctx):
	if ctx.env.docs:
		task = ctx(
			features="mallard",
			variable_definitions="Makefile.am",
		)
