config_but = 'config.but'

chapters = 5
appendices = 9

htmls = Split('IndexPage.html Contents.html') \
	+ map(lambda ch: 'Chapter' + str(ch + 1) + '.html', range(chapters)) \
	+ map(lambda ap: 'Appendix' + chr(ord('A') + ap) + '.html', range(appendices))
fixed_htmls = map(lambda fn: 'fixed/'+fn, htmls)

chm_config_but = 'chm_config.but'

buts = Split("""
	intro.but
	tutorial.but
	usage.but
	script.but
	var.but
	labels.but
	jumps.but
	pages.but
	sections.but
	usection.but
	functions.but
	callback.but
	attributes.but
	compilerflags.but
	basic.but
	registry.but
	generalpurpose.but
	flowcontrol.but
	file.but
	uninstall.but
	misc.but
	string.but
	stack.but
	int.but
	reboot.but
	log.but
	sec.but
	ui.but
	langs.but
	plugin.but
	silent.but
	compiler.but
	defines.but
	modernui.but
	library.but
	usefulfunc.but
	usefulinfos.but
	headers.but
	history.but
	build.but
	credits.but
	license.but
""")

import os
import re

Import('halibut env build_chm')

env.Append(ENV = {'PATH' : os.environ['PATH']})

build_dir = Dir(GetBuildPath('.')).abspath

replacement = '<a href="%s/\\1/' % env.subst('$PREFIX_DATA')

def fix_html(target, source, env):
	for i in range(len(source)):
		data = open(source[i].path,'rb').read()
		data = re.sub('<a href="../(Include|Stubs|Plugins|Contrib)/', replacement, data)
		open(target[i].path,'wb').write(data)
	return None

if build_chm:
	hhc_action = Action(r'cd \ && hhc "%s\nsis.hhp"' % (build_dir))
	execute = hhc_action.execute
	def rexecute(*args):
		return execute(*args) != 1 # hhc returns 1 on success
	hhc_action.execute = rexecute

	chm_builder = Builder(
		action = [
			Copy(build_dir, '${SOURCE.dir}/../style.css'),
			Copy(build_dir, '${SOURCE.dir}/chmlink.js'),
			Copy(build_dir, '${SOURCE.dir}/nsis.hhp'),
			Action('cd "%s" && "%s" ${SOURCES.abspath}' % (build_dir, halibut[0].abspath)),
			hhc_action
		]
	)

	env.Append(BUILDERS = {'HalibutCHM' : chm_builder})

	chm = env.HalibutCHM('NSIS.chm', [chm_config_but] + buts)
	env.Depends(chm, halibut)
	env.Depends(chm, '#Docs/style.css')
	env.Depends(chm, 'chmlink.js')
	env.Depends(chm, 'nsis.hhp')
	env.DistributeDoc(chm)

else:
	html_builder = Builder(
		action = [
			Copy(build_dir, '${SOURCE.dir}/../style.css'),
			Action('cd "%s" && "%s" ${SOURCES.abspath}' % (build_dir, halibut[0].abspath))
		]
	)
	
	html_fixer = Builder(action = fix_html, suffix = '.html', src_suffix = '.html')

	env.Append(BUILDERS = {'Halibut' : html_builder, 'FixHTML': html_fixer})

	html = env.Halibut(htmls, [config_but] + buts)
	env.Depends(html, halibut)
	env.DistributeDocs('#Docs/style.css')

	if env['PLATFORM'] == 'win32':
		env.DistributeDocs(html)
	else:
		fixed_html = env.FixHTML(fixed_htmls, htmls)
		env.DistributeDocs(fixed_html)
