#! /bin/sh
# implements nested file inclusion for control files, including wildcarding
# Copyright (C) 1998, 1999  Henry Spencer.
# 
# 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 2 of the License, or (at your
# option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
# 
# 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.
#
# RCSID $Id: _include,v 1.9 1999/04/10 22:51:25 henry Exp $
#
# output includes marker lines for file changes:
#	"#< filename lineno" signals entry into that file
#	"#> filename lineno" signals return to that file
# The lineno is the line number of the *next* line.
#
# If --inband is specified, errors are reported with a "#:message" line
# rather than on stderr.
#
# Lines which look like marker and report lines are never passed through.

usage="Usage: $0 [--inband] file ..."

PATH=/usr/local/sbin:/sbin:/usr/sbin:/usr/local/bin:/bin:/usr/bin
export PATH

inband=0

for dummy
do
	case "$1" in
	--inband)	inband=1		;;
	--help)		echo "$usage" ; exit 0	;;
	--version)	echo 1 ; exit 0		;;
	--)		shift ; break		;;
	-*)		echo "$0: unknown option \`$1'" >&2 ; exit 2	;;
	*)		break			;;
	esac
	shift
done

case $# in
0)	echo "$usage" >&2 ; exit 2	;;
esac

for f
do
	if test ! -r $f
	then
		if test "$inband" = 1
		then
			echo "#:cannot open configuration file \"$f\""
		else
			echo "$0: cannot open configuration file \"$f\"" >&2
		fi
		exit 1
	fi
	awk 'BEGIN {
		inband = "'"$inband"'"
		inb = ""
		if (inband)
			inb = "--inband "
		err = "cat >&2"
		lineno = 0
	}
	{
		if (lineno == 0)
			print "#<", FILENAME, 1
		lineno++
		# lineno is now the number of this line
	}
	/^#[<>:]/ {
		next
	}
	/^include[ \t]+/ {
		orig = $0
		sub(/[ \t]+#.*$/, "")
		if (NF != 2) {
			msg = "(" FILENAME ", line " lineno ")"
			msg = msg " include syntax error in \"" orig "\""
			if (inband)
				print "#:" msg
			else
				print ("_include: " msg) | err
			exit 1
		}
		newfile = $2
		if (newfile !~ /^\// && FILENAME ~ /\//) {
			prefix = FILENAME
			sub(/[^/]+$/, "", prefix)
			newfile = prefix newfile
		}
		print ""
		system("ipsec _include " inb newfile)
		print ""
		print "#>", FILENAME, lineno+1
		next
	}
	{ print }' $f
done
