#! /usr/bin/env python
# coding: utf-8
"""
 :copyright: (c) 2012 Philipp Benjamin Köppchen
 :license: GPLv3, see LICENSE for more details.
"""
import os.path
from optparse import OptionParser
from graygoo import Repository, UsageError


option_parser = OptionParser(usage='%prog [TEMPLATENAME] [key=value] ...')


def main():
    options, args = option_parser.parse_args()

    # determine templatename
    if not args:
        option_parser.error('please provide a template name')
    templatename = args[0]

    # determine template_args
    template_args = [pair.split('=', 1) for pair in args[1:]]

    if any(len(pair) != 2 for pair in template_args):
        option_parser.error('please provide all template arguments in the form key=value')

    template_args = dict(template_args)

    # prepare repository
    repo = Repository()
    repo.add_path(os.path.expanduser('~/.graygoo'))
    repo.add_buildins()

    # render the template
    try:
        template = repo.get_template(templatename)
        template.render('', template_args)
    except UsageError, exc:
        option_parser.error(unicode(exc))


if __name__ == '__main__':
    main()
