import os
import yaml
from mako.lookup import TemplateLookup
import pyrtek, pyrtek.rst, pyrtek.mako


mako_filter = pyrtek.mako.Filter(TemplateLookup(['../templates']))
rst_filter = pyrtek.rst.Filter()

filters = {'mako': mako_filter,
          'rst': rst_filter,
          'default': pyrtek.chain_filters(rst_filter, mako_filter)}

default_meta = {'__filter__': 'default',
                '__template__': 'default.mako'}

# rexp, repl, priority, func
rules = [(r'(.*)\.txt$', r'\1.html', 0,
          lambda s, d: pyrtek.Text(s, d, filters, default_meta))]


def main():
    # Load catalog, if it exists.
    try:
        with open('catalog.yaml') as f:
            catalog = yaml.load(f)
    except IOError:
        catalog = {}

    # The following block of code is executed inside the content directory.
    saved_cwd = os.getcwd();
    os.chdir('content')
    try:
        catalog = pyrtek.build(pyrtek.expand_rules(rules), catalog)
    finally:
        os.chdir(saved_cwd)

    # Save catalog.
    with open('catalog.yaml', 'w') as f:
        yaml.dump(catalog, f)


if __name__ == '__main__':
    main()