#!/usr/bin/python2.7

import sys
import xml.etree.cElementTree as et
from optparse import OptionParser

parser = OptionParser()
parser.add_option('-c', '--changeattributes', dest='change', action="append", nargs=3)
parser.add_option('-g', '--gentooclasspath', dest="gcp", action="store_true", default=False)
parser.add_option('-e', '--encoding', dest="encoding")
(options, args) = parser.parse_args()

changes = []
if options.change:
	for c in options.change:
		changes.append((c[0].split(),c[1], c[2]))

gcp = options.gcp
gcp_str = '${gentoo.classpath}'
gcp_sub = et.Element('classpath', path=gcp_str)

for file in args:
	tree = et.ElementTree(file=file)
	if gcp or options.encoding:
		for javac in tree.getiterator('javac'):
			if gcp:
				javac.attrib['classpath'] = gcp_str
			if options.encoding:
				javac.attrib['encoding'] = options.encoding
		for javadoc in tree.getiterator('javadoc'):
			if gcp:
				javadoc.attrib['classpath'] = gcp_str
			if options.encoding:
				javadoc.attrib['encoding'] = options.encoding
	for c in changes:
		elems, attr, value = c
		for elem in elems:
			for e in tree.getiterator(elem):
				e.attrib[attr] = value
	for junit in tree.getiterator('junit'):
		if gcp:
			junit.append(gcp_sub)
		junit.attrib['haltonfailure'] = 'true'

	f = open(file, 'w')
	tree.write(f)
	f.close()
