#!/usr/bin/env python3
##!/usr/local/bin/python3
# Copyright (C) 2019 Jesus Perez Lorenzo <https://jesusperez.pro>
# License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licences/gpl.html>

import os, sys, yaml, jinja2
from pathlib import Path

usage = f"{sys.argv[0]} template-path values-path"

def parseFileVars(filePath):
    if not Path(filePath).exists():
        print (f"Vars :file {filePath} not found")
        exit()
    data = {}
    with open(filePath) as f:
         data = yaml.load(f, Loader=yaml.FullLoader)
    return data

if len(sys.argv) < 2:
    print ("No arguments found\n" + usage)
    exit()

template_filename = sys.argv[1]
if len(sys.argv) >= 2:
   render_vars = parseFileVars(sys.argv[2])
else:
   render_vars = os.environ

if Path(template_filename).exists():
    root_path, file_path = os.path.split(template_filename)

    environment = jinja2.Environment(loader=jinja2.FileSystemLoader(root_path))
    output_text = environment.get_template(file_path).render(render_vars)
else:
    output_text = f"File {template_filename} not found"

print (output_text)

