#!/usr/bin/env python

from lxml import etree as ET
from lxml.etree import XMLSyntaxError

from systematic.shell import Script, ScriptError

script = Script()
script.add_argument('-c', '--remove-comments', action='store_true', help='Remove comments')
script.add_argument('-r', '--replace', action='store_true', help='Replace original file')
script.add_argument('paths', nargs='*', help='Filenames to process')
args = script.parse_args()

if not len(args.paths):
    script.exit(1, script.get_usage())

parser = ET.XMLParser(remove_blank_text=True, remove_comments=args.remove_comments)
for path in args.paths:
    try:
        tree = ET.parse(path, parser=parser)
    except IOError as error:
        script.message(str(error))
        continue

    except XMLSyntaxError as emsg:
        script.message(emsg)
        continue

    if args.replace:

        output = ET.tostring(tree, pretty_print=True)
        old = open(path, 'r').read()
        if old!=output:
            try:
                script.log.debug('Writing file: {0}'.format(path))
                open(path, 'w').write(ET.tostring(tree, pretty_print=True))
            except IOError as e:
                script.exit(1, 'Error writing to file {0}: {1}'.format(path, e))

        else:
            script.log.debug('XML tree was not modified, not writing')

    else:
        print ET.tostring(tree, pretty_print=True)

