#! /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.in,v 1.17 2003/01/06 21:44:04 sam 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.
#
# 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 file ..."
me="ipsec _include"

for dummy
do
	case "$1" in
	--inband)				;;	# back compatibility
	--help)		echo "$usage" ; exit 0	;;
	--version)	echo "$me $IPSEC_VERSION" ; 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 ! "$f" = "/etc/ipsec.conf"
		then
			echo "#:cannot open configuration file \'$f\'"
			if test "$f" = "/etc/ipsec.secrets"
			then
				echo "#:Your secrets file will be created when you start FreeS/WAN for the first time."
			fi
			exit 1
		else
			exit 1
		fi
	fi
done

awk 'BEGIN {
	wasfile = ""
}
FNR == 1 {
	print ""
	print "#<", FILENAME, 1
	lineno = 0
	wasfile = FILENAME
}
{
	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 "\""
		print "#:" msg
		exit 1
	}
	newfile = $2
	if (newfile !~ /^\// && FILENAME ~ /\//) {
		prefix = FILENAME
		sub("[^/]+$", "", prefix)
		newfile = prefix newfile
	}
	system("ipsec _include " newfile)
	print ""
	print "#>", FILENAME, lineno + 1
	next
}
{ print }' $*
