#!/usr/bin/env python

import sys
from lxml import etree

# We will be filtering the children of the elements later,
# to remove comments. Let's define a function to filter the stream:
def not_comment(x):
  return not 'comment' in x.tag

if len(sys.argv) != 4:
  print "Usage: %s filename xpath new_value" % sys.argv[0]
  sys.exit(1)

# The spud file to modify
filename = sys.argv[1]

# The path to the node in the tree
xpath = sys.argv[2]

# The value to set
newval = sys.argv[3]

# Open it up
tree = etree.parse(open(filename))
root = tree.getroot()
rootname = root.tag

# Here we translate the spud-xpath to real XML xpath
node = tree.xpath("/" + rootname + xpath)[0]

# Now we need to find the <real_value> or <integer_value> etc. tag underneath it.
child = filter(not_comment, node.getchildren())[0]
child.text = newval

newfile = open(sys.argv[1], "w")
tree.write(newfile, encoding="utf8", xml_declaration=True)
