#!/usr/bin/env python
#
# $Source: /home/blais/repos/cvsroot/arubomu/bin/arubomu-descarga-filter,v $
# $Id: arubomu-descarga-filter,v 1.14 2004/07/02 00:08:23 blais Exp $
#

"""arubomu-descarga-filter <email-file>

Help the descarga email update with personalized one liner format.

"""

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


import sys
import re, string
import time
import quopri, StringIO

import locale
locale.setlocale(locale.LC_ALL, 'en_CA')



#----- variables -----

commre = re.compile( '^\s*#.*$' )
empre = re.compile( '^\s*$' )


def readIn(file):
    """Reads an entry book file, removes comments, and split in chunks
    separated by whitespace lines."""

    lines = file.readlines()
    lines.append( "" ) # make sure we can parse the last entry

    chunklist = []
    curchunk = []
    for l in lines:
        if commre.match(l):
            continue
        if empre.match(l):
            if curchunk:
                chunklist.append( curchunk )
                curchunk = []
            else:
                pass
        else:
            curchunk.append( string.strip(l) )
    return chunklist


def quoin(s):
    if ',' in s:
        return '"%s"' % s.strip()
    return s.strip()

class Entry:
    ttre = re.compile('^(.*)\s*\(\s*CD\s*(.*)\s*\)')
    urlre = re.compile('.*"\s*http://www.descarga.com/cgi-bin/db/(.*)\s*"')
    
    def __init__(self, lines):
        self.valid = 0
        if len(lines) < 3:
            return
        self.artist = string.capwords(lines[0])
        mo = Entry.ttre.match(lines[1])
        if not mo:
            return
        (self.title, self.label) = mo.groups()

        self.descarga_no = ''
        for l in lines:
            mo = Entry.urlre.match(l)
            if mo:
                self.descarga_no = mo.group(1)

        self.year = time.strftime( "%Y", time.localtime( time.time() ) )

        self.valid = 1

    def __repr__(self):
        s = string.join(\
            map( quoin, ['- salsa', self.artist, self.title,
                         self.label, self.year]), ', ')

        if self.descarga_no:
            s += '\n'
            s += '  descarga="TL-%s"' % quoin(self.descarga_no)

        return s




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

    # read in file
    if len(args) > 0:
        try:
            file = open(args[0], 'r')
        except IOError, e:
            print >> sys.stderr, e
            sys.exit(1)
    else:
        file = sys.stdin

    # convert from quoted-printable
    ofile = StringIO.StringIO()
    quopri.decode(file, ofile)

    oofile = StringIO.StringIO(ofile.getvalue())
    
    rawchunks = readIn(oofile)
    file.close()

    for chk in rawchunks:
        e = Entry(chk)
        print
        print
        if e.valid:
            print e
            print
            print string.join( map( lambda x: '  ' + x, chk[2:] ), '\n')
            ##print
            ##print string.join( map( lambda x: '  [ %s ]' %x, chk[:2] ), '\n')
        else:
            print string.join( chk, '\n')
        print

# Run main if loaded as a script
if __name__ == "__main__":
    main()

