#!/usr/bin/env python2

'''
The MIT License (MIT)

Copyright (c) 2015 Sascha Spreitzer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import sys
import os
import getopt
import json

try:
	import yaml
	YAML=True
except:
	YAML=False

from jinja2 import Template

def renderenv(t):
	return Template(t).render(os.environ)

def renderjson(t, j):
	return Template(t).render(json.loads(j))

def renderyaml(t, y):
	return Template(t).render(yaml.load(y))

def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], 'e:j:y:')
		for opt, arg in opts:
			if opt == '-e':
				print renderenv(open(arg).read())
			elif opt == '-j':
				print renderjson(open(arg).read(), sys.stdin.read())
			elif opt == '-y':
				if YAML:
					print renderyaml(open(arg).read(), sys.stdin.read())
				else:
					print "yaml not supported - install pyyaml"
					sys.exit(3)
	except getopt.GetoptError:
		print "ninja2 <-e | -j | -y> template.j2"
		print "    -e render from environment"
		print "    -j render from json file"
		print "    -y render from yaml file"
		print ""
		print "  read a jinja2 template from file and values from stdin"
		print "  either environment or json or yaml"
		print "  (c) 2015 Sascha Spreitzer, MIT License"
		sys.exit(2)

if __name__=="__main__":
	main()

