#!/bin/sh
# pp - a tiny template preprocessor
#
#   pp [-d] file [arg ...]
#
# Lines between two lines containing only "#!" are sh(1) code and run as
# is.  Everything else is printed, after the shell has expanded $var,
# $(cmd) and `cmd` in it (like an unquoted heredoc), so a template can
# use its arguments as $1, $2, ... and any exported variable.  Double
# quotes pass through untouched.
#
# If $PPLIB names a file it is sourced before the template runs, which
# is how templates get their helper functions (see share/lib.sh).
#
#   -d   print the generated shell script instead of running it

usage() { printf 'usage: pp [-d] file [arg ...]\n' >&2; exit 1; }

dump=0
[ "$1" = -d ] && { dump=1; shift; }
[ $# -ge 1 ] || usage
file=$1; shift
[ -r "$file" ] || { printf 'pp: %s: cannot read\n' "$file" >&2; exit 1; }

script() {
	[ -n "${PPLIB:-}" ] && printf '. "%s"\n' "$PPLIB"
	awk '
	/^[ \t]*#!$/	{ if (text) { print "PP_EOF"; text = 0 }; code = !code; next }
	NR == 1 && /^#!./	{ next }
	code		{ print; next }
			{ if (!text) { print "cat <<PP_EOF"; text = 1 }; print }
	END		{ if (text) print "PP_EOF" }
	' "$file"
}

if [ $dump = 1 ]; then
	script
else
	sh -c "$(script)" "pp:$file" "$@"
fi
