#!/bin/sh
##
##  gomplate-generate
##  generate a configuration snippets from a template the convenient way:
##  - reads the parameters in YAML format from stdin
##  - reads the defaults for parameters in YAML format from template "$name:params"
##  - reads the configuration snippets from template "$name:template"
##
##  Example:
##
##  $ cat templates.txt
##  {{ define "hello:params" -}}
##  type: lovely
##  name: world
##  {{ end -}}
##  {{ define "hello:template" -}}
##  Hello {{ .type }} {{ .name }}!
##  {{ end -}}
##
##  $ gomplate-generate template.txt hello </dev/null
##  Hello lovely world!
##
##  $ echo "{ type: beautyful, name: galaxy }" | gomplate-generate template.txt hello
##  Hello beautyful galaxy!
##
##  $ echo "name: friend" | gomplate-generate template.txt hello
##  Hello lovely friend!
##

template_path="$1"
template_name="$2"

cmd="@l_prefix@/bin/gomplate"
cmd="$cmd -d params=stdin:?type=application/yaml"
cmd="$cmd -i \"{{ template \\\"$template_name:template\\\""
cmd="$cmd (coll.Merge (ds \\\"params\\\") (tmpl.Exec \\\"$template_name:params\\\" | yaml)) }}\""

if [ -f $template_path ]; then
    cmd="$cmd -t $template_path"
elif [ -d $template_path ]; then
    for template_file in $template_path/*; do
        if [ -f $template_file ]; then
            cmd="$cmd -t $template_file"
        fi
    done
fi

eval "$cmd"

