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

import handlerbase, utilities

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

	def collect(self, amfile):
		if not amfile.is_defined("SUBDIRS"):
			amfile.rulef.subdirs = ['.']
		else:
			amfile.rulef.subdirs = amfile.definition_rec("SUBDIRS")

		if amfile.rulef.subdirs == ['$(AUTODIRS)']:
			subdirs = ['.']
			for entry in os.listdir(amfile.dirname):
				if entry == 'CVS' or entry[0] == '.':
					continue
				if not os.path.isdir(amfile.dirname + "/" + entry):
					continue
				if os.path.exists(amfile.dirname + "/" + entry + "/Makefile.am"):
					subdirs.append(entry)

			amfile.defs["SUBDIRS"] = subdirs
			amfile.rulef.subdirs = subdirs			

		for subdir in amfile.rulef.subdirs:
			match = variablere.match(subdir)
			if match:
				if not amfile.conds.has_key(match.group(1)):
					utilities.print_error("%s: SUBDIRS contains variable %s\n" % (amfile.filename, match.group(1)))
				else:
					amfile.rulef.conds[match.group(1)] = amfile.conds[match.group(1)]
					del amfile.conds[match.group(1)]

register_handler(AutoDIRSHandler())
