#!/bin/sh
#
# Copyright (c) 2003-2014 SUSE Linux GmbH, Nuernberg, Germany.
# All rights reserved.
#
# Authors: Lars Mueller <lmuelle@suse.com>
#

#
# check if we are started as root
# only one of UID and USER must be set correctly
#
[ -n "$UID" ] || UID="$(id -ru)"
if test "$UID" != 0 -a "$USER" != root; then
    echo "You must be root to start $0."
    exit 1
fi

BASENAME=$( basename $0)
warnMessage()
{
	tput bold
	echo -n "Warning: "
	tput sgr0
	echo $1
}

errorMessage()
{
	tput bold
	echo -n "Error: "
	tput sgr0
	echo $1
}

#
# check for named settings
#
if [ ! -f /etc/sysconfig/named ]; then
	errorMessage "No /etc/sysconfig/named found!  Exiting."
	exit 1
fi
. /etc/sysconfig/named

# Check for NAMED_CONF_META_INCLUDE_FILE or set it to our default if we
# make use of this script.
if [ -z "${NAMED_CONF_META_INCLUDE_FILE}" ]; then
	for script in ${NAMED_INITIALIZE_SCRIPTS}; do
		if [ "${script}" = "${BASENAME}" -o \
		"${script}" = "/usr/share/bind/createNamedConfInclude" ]; then
			NAMED_CONF_META_INCLUDE_FILE="/var/lib/named/named.conf.include"
			break
		fi
	done
	# If NAMED_CONF_META_INCLUDE_FILE is still empty skip silent.
	test -z "${NAMED_CONF_META_INCLUDE_FILE}" && exit 0
fi

DATE=$( LANG=POSIX date)
cat << EOF > ${NAMED_CONF_META_INCLUDE_FILE}
#
# This file is autogenerated by /usr/share/bind/createNamedConfInclude
# on ${DATE}.  Don't edit it manually.
#
# Add additional configuration files which should be added to /etc/named.conf
# by this mechanism to NAMED_CONF_INCLUDE_FILES in /etc/sysconfig/named.  This
# is possible with the YaST sysconfig or any other editor.
#

EOF

for file in ${NAMED_CONF_INCLUDE_FILES}; do
	# prepend the default include directory if the filename is relative
	case "$file" in
		/*) ;;
		*) file="/etc/named.d/${file}" ;;
	esac
	if [ ! -f "${file}" ]; then
		warnMessage "File, ${file} to include not found!  Skipping."
		continue
	fi
	echo "include \"${file}\";" >> ${NAMED_CONF_META_INCLUDE_FILE}
done

exit 0
