# -*-python-*-
# vim: ts=4

import handlerbase

class KCFGHandler(handlerbase.HandlerBase):
	def __init__(self):
		pass

	def extensions(self):
		return ['.kcfgc']

	def source(self, program, base, ext):
		sourcename = base

		rulef = program.amfile.rulef
		
		sourcedir = ''
		if program.amfile.in_srcdir( base + ext ):
			sourcedir = rulef.source
		else:
			sourcedir = rulef.build

		kcfg = "unknown.kcfg"
		kcfgre = re.compile("File=(.*\.kcfg)")
		lines = open(program.amfile.dirname + "/" + base + ext).readlines()
		for line in lines:
			match = kcfgre.match(line)
			if match:
				kcfg = match.group(1)
					
		rulef.insertTarget(rulef.build + sourcename + ".cpp",
				   rulef.build + sourcename + ".h")
		rulef.insertTarget(rulef.build + sourcename + ".h",
					[sourcedir + base + ".kcfgc",
					 sourcedir + kcfg,
					 "$(KCFG_DEPENDENCIES)"],
					["@echo 'creating " + rulef.build + sourcename + ".h'",
					 "@echo 'creating " + rulef.build + sourcename + ".cpp'",
					 "@$(KCONFIG_COMPILER) -d " + rulef.build + " " + sourcedir + kcfg + " " + sourcedir + base + ".kcfgc ||"
						"( rm -f " + rulef.build + sourcename + ".h; false )"])
			
		program.handle_source(sourcename, ".cpp")

		program.amfile.add_define(program.canon_name + "_COMPILE_FIRST",
								  sourcename + ".h")
			
		program.cleanfiles.extend([sourcename + ".cpp",
					   sourcename + ".h"])

register_handler(KCFGHandler())
