#!/bin/sh
#
# Copyright (C) 2001-2013 Graeme Walker <graeme_walker@users.sourceforge.net>
# 
# 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 <http://www.gnu.org/licenses/>.
# ===
#
# expand.sh
#
# Expands "#include#<file>#" directives.
# 
# Only does one sustitution per line. Directives which start the line are
# multi-line. Those within a line are one-line, expanded in-place.
#
# The "-t" switch can be used to suppress expansion where the included
# file has an extension of ".html".
#
# In edit mode (--edit) the specified file is modified in-place. With this
# switch the exit value is 0 (shell true) if the file is modified in any
# way. This allows for recursive expansion using a shell while loop.
#
# usage: expand.sh [-a <awk>] [-t] { --edit <file> | [<file> ...] }
#

Usage()
{
	echo usage: `basename $0` '[-a <awk>] [-t] { --edit <file> | [<file> ...] }' >&2
}

tmp="/tmp/`basename $0`.$$.tmp"

awk=`( gawk 'END {print "gawk"}' ; nawk 'END {print "nawk"}' ; echo awk ) 2>/dev/null < /dev/null | head -1`
if test "${1}" = "-a"
then
	shift
	awk="${1}"
	shift
fi

expand_html="1"
if test "${1}" = "-t"
then
	shift
	expand_html="0"
fi

edit="0"
if test "${1}" = "--edit"
then
	shift
	edit="1"
	if test $# -ne 1 ; then Usage ; exit 1 ; fi
fi

Expand()
{
	${awk} -v expand_html="${expand_html}" -v cat="${awk} '{print}'" '
	BEGIN { modified = 0 }
	{
		line = $0
		if( match(line,"#include#[^#]*#") )
		{
			rstart = RSTART
			directive = substr(line,RSTART,RLENGTH)
			path = substr(line,RSTART+9,RLENGTH-10)

			if( !expand_html && match(path,".html$") )
			{
				print line
			}
			else
			{
				modified = 1
				head = substr(line,1,rstart-1)
				if( match(head,"^[\t ]*$") )
				{
					system( cat "  " path )
				}
				else
				{
					getline text <path
					if( length(text) == 0 )
						printf( "expand.sh: warning: line %d: empty text sustitution for %s\n" , NR , path ) >"/dev/fd/2"
					sub( directive , text , line )
					print line
				}
			}
		}
		else
		{
			print line
		}
	}
	END { exit ! modified }
	' $@
}

if test "${edit}" -eq 1
then
	# (use cp rather than mv here to protect read-only files)
	Expand $@ > "${tmp}" && cp "${tmp}" "${1}"
	rc=$? ; rm -f "${tmp}" 2>/dev/null ; exit "${rc}"
else
	Expand $@
	true
fi

