#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/old/bin/fix-catalogs,v $
# $Id: fix-catalogs,v 1.2 2004/02/07 01:16:38 blais Exp $
#

"""fix-catalogs [<options>] <file>

Fix old catalog format to newer one.

"""
# Used like this:
#
# for i in   */*.xml ; do echo $i ; \
#   b=/tmp/orig/$(basename $i) ; cp $i $b ; \
#   ~/p/arubomu/old/bin/fix-catalogs $b > /tmp/a.xml ; \
#   xmllint-elementtree --format /tmp/a.xml > $i ; \
#   diff -y --suppress-common-lines $b $i ; done

__version__ = "$Revision: 1.2 $"
__author__ = "Martin Blais <blais@furius.ca>"


import sys, os

from elementtree import ElementTree

from pprint import pprint



def getiteratorp(self, tag=None, index=0, parent=None):
    """A version of Element.getiterator that also gives the parent. This is
    useful when you want to replace a node."""

    nodes = []
    if tag == "*":
        tag = None
    if tag is None or self.tag == tag:
        nodes.append( (self, index, parent) )
    i = 0
    for node in self._children:
        nodes.extend(node.getiteratorp(tag, i, self))
        i += 1
    return nodes

ElementTree._Element.getiteratorp = getiteratorp


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__)
    opts, args = parser.parse_args()

    if len(args) != 1:
        raise parser.error("Please specify a single input file.")
    fn = args[0]

    try:
        tree = ElementTree.parse(fn)
        root = tree.getroot()
        ##ElementTree.dump(root)
    except IOError, e:
        raise SystemExit("Error: couldn't read file (%s):" % fn + str(e))

    oldcats = []
    for c in ['descarga', 'amazon', 'cddb']:
        it = root.getiteratorp(c)
        for i, idx, parent in it:
            ##print ElementTree.tostring(i)
            parent.remove(i)
            oldcats.append(i)

    if oldcats:
        # create new element
        newcats = ElementTree.Element('catalogs')
        for oldc in oldcats:
            oldc.set(u'name', oldc.tag)
            oldc.tag = u'catalog'
            newcats.append(oldc)

        # find parent album to add to.
        it = root.getiterator('album')
        assert len(it) == 1
        album = it[0]

        # find tag to insert before of
        t = None
        for tn in ['songs', 'musicians', 'reviews', 'comments', 'notes']:
            t = album.find(tn)
            if t != None:
                break
        if t != None:
            idx = album._children.index(t)
            album.insert(idx, newcats)
        else:
            album.append(newcats)

    tree.write(sys.stdout, encoding='iso-8859-1')
    print

if __name__ == '__main__':
    main()

