#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/bin/arubomu-rotate-songs,v $
# $Id: arubomu-rotate-songs,v 1.1 2005/02/07 23:10:39 blais Exp $
#

"""
Rotate the number of songs by a specified increment.

This is used for idiots who can't set their ripper programs right.
"""

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


import sys, os, shutil

from elementtree.ElementTree import ElementTree
from elementtree_pretty import write_pretty

from arubomu.rip import load


xmlindent = os.environ.get('XMLLINT_INDENT', '   ')


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

    parser.add_option('-i', '--increment', action='store', type='int',
                      default=1,
                      help="Increment for the song numbers.")

    parser.add_option('-R', '--replace', action='store_true',
                      help="Replace the input file.")

    opts, args = parser.parse_args()

    if len(args) != 1:
        parser.error('You need to specify a single XML file.')
    xmlfn = args[0]

    a = load(xmlfn, True)

    if opts.replace:
        shutil.copyfile(xmlfn, xmlfn + '.bak')
        outf = open(xmlfn, 'w')
    else:
        outf = sys.stdout

    for disc in a.album.discs.itervalues():
        for song in disc.songs.itervalues():
            song.no += opts.increment

    tree = ElementTree(a.toxml())
    write_pretty(tree, outf, encoding='ISO-8859-1', indent=xmlindent)
        
if __name__ == '__main__':
    main()
