#! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010 (ita)

VERSION='0.0.1'
APPNAME='dynamic_header_test'

top = '.'
out = 'build'

def options(opt):
	opt.load('compiler_cxx')

def configure(conf):
	conf.load('compiler_cxx')

def build(bld):
	bld.program(source='main.cpp', target='app', includes='.')

# --------------------------------------------------------------------
# Dynamic header creation, the file "a.h" from main.cpp is created
# during the build. You may use this code sample to create more complicated
# dynamic header generators

from waflib import Task
from waflib.Tools.cxx import cxx

class test(Task.Task):
	run_str = 'touch ${TGT}'

def runnable_status(self):
	ret = super(cxx, self).runnable_status()

	try:
		shared = self.generator.bld.shared_tasks
	except AttributeError:
		shared = self.generator.bld.shared_tasks = {}

	if ret != Task.ASK_LATER:
		add = False

		# first pass over the unresolved files found by the scanner
		for x in self.generator.bld.raw_deps[self.uid()]:
			if x == 'a.h':
				tgt = self.generator.path.find_or_declare(x)
				try:
					tsk = shared[tgt]
				except KeyError:
					tsk = shared[tgt] = self.generator.create_task('test', [], tgt)
					self.set_run_after(tsk)
					self.generator.bld.producer.outstanding.append(tsk)
					add = True
		if add:
			# remove cache entries to force a clean scanner execution
			delattr(self, 'cache_sig')
			self.generator.bld.cache_nd = {}
			del self.generator.bld.task_sigs[(self.uid(), 'imp')] # will have to rescan the C file
			return self.runnable_status()

		# second pass over the existing nodes - corresponding tasks are still necessary
		for x in self.generator.bld.node_deps[self.uid()]:
			if x.name == 'a.h':
				try:
					tsk = shared[x]
				except KeyError:
					tsk = shared[x] = self.generator.create_task('test', [], x)
					self.set_run_after(tsk)
					self.generator.bld.producer.outstanding.append(tsk)
					add = True
		if add:
			# no need to rescan anything, but recompute the signature after the dependent task is executed
			delattr(self, 'cache_sig')
			return self.runnable_status()
	return ret

cxx.runnable_status = runnable_status

