#!/bin/sh

die() {
    echo "$@" >&2
    exit 2
}

mktmpl() {
    #
    # Make temporary template for git-commit and print its path
    #
    local mtmpl_name="$1"; shift
    local mtmpl_path
    local tmpl_path
    mtmpl_path="$HOME/.gittum/template/$mtmpl_name"
    test -f "$mtmpl_path" || die "no such meta-template: $mtmpl_path"
    bash -n "$mtmpl_path" || die
    tmpl_path="/.$(mktemp -t gittum-metacm.XXXXXXXX)"
    bash "$mtmpl_path" "$@" > "$tmpl_path" || die "template script exited with bad state: $?"
    printf %s "$tmpl_path"
}

main() {
    local name="$1"; shift
    local tmpl
    local interactive=true
    test -n "$1" && interactive=false
    tmpl="$(mktmpl "$name" "$@")"
    if $interactive;
    then
        git commit --verbose --template="$tmpl"
    else
        git commit -F "$tmpl"
    fi
    rm "$tmpl"
}

main "$@"