#!/usr/bin/env bash # # Portimg uses Crux port-like system for creating software deployment images. # Copyright (C) 2016 Aaron Ball # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # # Provides *very* basic templating functionality. Interpolates basic jinja # variable syntax ( "{{ variable }}" ). # # Template variables are replaced with matching bash environment variabes. This # means that template variables can only contain upper case, lower case, # numbers, underscores. All non-conforming variables are ignored. # # @param src Path to template file to interpolate # @param dest Destination to copy the interpolated template to # function template { local src=${1:-} local dest=${2:-} local _delim # Regex delimiter (use an uncommon character please) local _tmp # Path to the tmp copy of the original template file local _oldifs # Old value of IFS (for changing it back) local _filevars # List of valid variable references found in the template file local _varstr # Template string calling the variable (eg: {{ varname }}) local _varname # Name of the actual variable (eg: {{ varname }} == varname) # Pick a really weird delimiter to avoid possible regex conflict _delim=$'\001' # Copy the template to a temp location so we don't work on the original _tmp=$(mktemp tmp.template.XXXXXXXX) cp -p ${src} ${_tmp} # Read all unique template variables specified in the file _filevars=("$( grep -o '{{ [_[:alnum:]]\+ }}' ${_tmp} | sort | uniq)") _oldifs=${IFS} IFS=$'\n' for _varstr in ${_filevars[@]}; do # Strip '{{ ' and ' }}' from varstr to get variable name _varname="${_varstr:3:-3}" # Skip any unset but referenced variables if [ -z "${!_varname:-}" ]; then printf \ "WARN: Unbound variable '%s' in template '%s'.\n" \ "${_varname}" \ "${src}" >&2 continue fi # If variable is set, then find and replace sed -i "s${_delim}${_varstr}${_delim}${!_varname}${_delim}g" "${_tmp}" done IFS=${_oldifs} # Move the modified version into place, creating any leading dirs if necessary install -D "${_tmp}" "${dest}" rm -f "${_tmp}" }