#!/bin/bash
# Small library for template file handling.
# This eliminates the need for nasty <<EOF constructs
# even when some values have to be manually filled in.
#
# This routine takes the file and replaces the given patterns
# (in regular use). Patterns are specified in a pattern file
# as e.g. /__KVERSION__/$KERN_VER/
# one pattern per line, no leading/trailing junk (a g is appended automatically)

# Patterns will be passed through an eval in double quotes.
# This means any double quotes in the pattern or replacement have to be
# escaped. On the other hand, this allows us to use bash variables at all.
# In essence, specify patterns as you would stuff in "".

# No standard patterns are defined at all.
# If you need to escape certain sequences, either re-design your
# patterns or add a /__NO_OP__// replacement that you can use to split
# up stuff that would otherwise match.

# $1: file to be printed
# $2: file containing patterns
# This function returns the final file to stdout
function run_template()
{
  local RANDNAME="$TMP_DIR/template.$RANDOM"
  local pattern
  while [ -e $RANDNAME ] ;do
    echo "Warning: template file $RANDNAME already exists" >&2
    RANDNAME="$TMP_DIR/template.$RANDOM"
  done
  cat "$1" >$RANDNAME # no cp, so /dev/stdin etc. work
  while read pattern ;do
    eval "sed -i -e \"s${pattern}g\" $RANDNAME"
    # we need an eval so that $vars in the pattern get expanded
  done <$2
  cat $RANDNAME
  rm -f $RANDNAME
  return 0
}
