#!/usr/bin/python
"""interpolate2fancy

Convert Blosxom [http://www.blosxom.com/] flavour templates
[http://www.blosxom.com/documentation/users/flavour.html] from a)
the default Blosxom interpolation style (e.g. $variable) or b)
interpolate_conditional
[http://www.blosxom.com/plugins/interpolate/interpolate_conditional.htm] plugin
style (e.g. ?{$variable output goes here}) plugin to that expected
by the interpolate_fancy
[http://www.blosxom.com/plugins/interpolate/interpolate_fancy.htm]
plugin.

Generates an altered set files in the current working directory.  Each is
named according to the original, suffixed by ".fancy".

Usage: python interpolate2fancy.py /path/to/flavour/files/*.flavour_to_convert
"""

__version__ = "0+1i"
__date__ = "2003-08-31"
__author__ = "Rael Dornfest [http://raelity.org/] <rael@raelity.org>"
__copyright__ = "Copyright 2003 Rael Dornfest"
__license__ = "http://creativecommons.org/licenses/by/1.0/"

import re

if __name__ == '__main__':
    import sys, os, re

    if sys.argv[1:]:
        files = sys.argv[1:]

        conditions = {'<':'lt', '>':'gt', '=':'eq', '!=':'ne'}

        for file in files:
            filename = os.path.basename(file)

            try:
                flavourfh = open(file, 'r')
                contents = flavourfh.read()
                flavourfh.close()
            except: 
                print "couldn't read %s" % file
                continue

            contents = re.sub(r'\$(\w[\w:]*)', r'<$\1 />', contents)
            contents = re.sub(r'\?\{(!?)<\$(\w[\w:]*) />((?:[!<=>]{1,2}[^\s]+)?)\s+([^\}]*)\}', r'<?\1$\2{{{\3}}}>\4</?>', contents)
            contents = re.sub(r'\{{3}\}{3}', '', contents)
            contents = re.sub(r'\{\{\{([!>=<]{,2})(.+?)\}\}\}>', lambda m: (' %s="%s">' % (conditions[m.group(1)], m.group(2))), contents)

            try:
                flavourfh = open(file+'.fancy', 'w')
                flavourfh.write(contents)
                flavourfh.close()
            except: 
                print "couldn't write to %s" % file+'.fancy'

    else:
        print "Usage: python interpolate2fancy.py *.flavour_to_convert"
