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

import os, re

variablere = re.compile('\$[{(]([^({})]*)[})]$')
variablesre = re.compile('([^\$]*)\$[{(]([^({})]*)[})](.*)')
extre = re.compile('(.*)(\.[^.]*)$')
definere = re.compile('\s*([^+=\s]*)\s*(\+?)=(.*)$')
cppext = [".cpp", ".cc", ".C", ".cxx", ".c++"]
hext = [".h", ".H", ".hh", ".hxx", ".hpp", ".h++"]

_topsrcdir = ""
subst_vars = {}

def list_source_files(dirname):
	cppfiles = []
	hfiles = []
	for file in os.listdir(dirname):
		match = extre.match(file)
		if not match:
			continue
		base = match.group(1)
		ext = match.group(2)

		if not ext in cppext and not ext in hext:
			continue
		if base.endswith('.moc') or base[0] == '.':
			continue
		found = 0
		for cpp_ext in cppext:
			all_cpp = ".all_%s.%s" % (cpp_ext, cpp_ext)
			if file.endswith(all_cpp):
				found = 1
		if found:
			continue
		if ext in cppext:
			cppfiles.append((base, ext))
		else:
			hfiles.append((base, ext))

	return (cppfiles, hfiles)

default_force = 1

def write_if_changed(filename, lines, force = 0):
	# I'm not convinced any longer we can make use of this
	force = default_force
	if not force and os.path.exists(filename):
		index = 0
		while index < len(lines):
			if string.find(lines[index], '\n', 0, -1) != -1:
				split = string.split(lines[index], '\n')
				if not len(split[-1]):
					split = split[:-1]
				for si in range(0, len(split)):
					split[si] = split[si] + '\n'
				lines[index:index+1] = split
				index = index + len(split)
			else:
				index = index + 1
		new_lines = open(filename).readlines()
		if new_lines == lines:
			return
		else:
			print filename, 'changed'
			pass
	
	open(filename, 'w').writelines(lines)

import string

def parse_autoconf(full=0):
	tracelines = []

	tracevalid = not full and os.path.exists(".autoconf_trace")
	if tracevalid and os.path.getmtime("configure.in") > \
	   os.path.getmtime(".autoconf_trace"):
		tracevalid = 0

	if tracevalid and os.path.getmtime("aclocal.m4") > \
	   os.path.getmtime(".autoconf_trace"):
		tracevalid = 0

	if tracevalid:
		tracelines = open( ".autoconf_trace" ).readlines()
			
	if not len(tracelines):
		traces = "autoconf -t AC_SUBST -t AC_CONFIG_FILES -t AC_CONFIG_AUX_DIR -t AC_CONFIG_HEADERS"
		tracelines = os.popen( traces ).readlines()
		if not len(tracelines):
			print 'couldn\'t call', traces
			sys.exit(1)
		open(".autoconf_trace", 'w').writelines(tracelines)
		
	subst = {}
	files = []
	headers = []
	auxdir = '.'
	for line in tracelines:
		splitted = string.split(string.strip(line), ':')
		if splitted[2] == 'AC_SUBST':
			value = ""
			if len(splitted) == 5:
				if len(splitted[4]) and splitted[4][0] == "'":
					value = splitted[4][1:-1]
			subst[splitted[3]] = value
		elif splitted[2] == 'AC_CONFIG_FILES':
			files.extend( string.split( splitted[3] ) )
		elif splitted[2] == 'AC_CONFIG_HEADERS':
			headers.extend( string.split( splitted[3] ) )
		elif splitted[2] == 'AC_CONFIG_AUX_DIR':
			auxdir = splitted[3]
		else:
			print splitted, 'doesn\'t contain the traced macros'

	if auxdir == '.':
		return subst, files, headers, '$(top_srcdir)'
	else:
		return subst, files, headers, '$(top_srcdir)/' + auxdir

import re

def canon_name(name):
	return re.sub('[^a-zA-Z0-9_]', '_', name)

sys_exit_code = 0

import sys

def print_error(string):
	sys.stderr.write("ERROR:")
	sys.stderr.write(string)
	global sys_exit_code
	sys_exit_code = 1
	
