#!/bin/bash

. ${TOOLKIT}-functions.sh

gen_template()
{
	local in=$1
	local out=$2
	local name=$3
	local icon=$4
	local net=$5

	sed -e "s}@NAME@}$name}g" -e "s}@ICON@}$icon}g" -e "s}@NET@}$net}g" \
		"$in" >$out
}


# initialize kusa defines temp db
#
:> $MODLOCALDB
echo "[temp]" >>$MODLOCALDB


outdir="templates.tmp"

rm -rf $outdir
mkdir $outdir


# templates
#
echo -en "  generating auto templates ...\n    "
for name in $(ls templates)
do
	echo -n "$name "
	out="$outdir/$name.cfg"

	echo "# auto generated template for: $name" >$out
	echo "#" >>$out
	echo "# ::do_not_edit::" >>$out
	echo "# ::maintainer::" >>$out
	echo "#" >>$out
	cat "templates/$name" >>$out
done
echo


# icons
#
icons=$(jtconf --listvars nagios_images)

echo -en "  generating node/icons templates ...\n    "

in=$(filepath 'nagios-tpl-node-icon.in')

for name in $icons
do
	echo -n "$name "
	out="$outdir/node-$name.cfg"
	icon=$(jtconf nagios_images.$name)
	gen_template "$in" "$out" "$name" "$icon" ""
done
echo


# generate nagios.cfg template
#
net_in=$(filepath 'nagios-tpl-net.in')
node_in=$(filepath 'nagios-tpl-net-node.in')
icon_in=$(filepath 'nagios-tpl-net-node-icon.in')

srcfile=$(filepath nagios.cfg)
outfile="nagios.cfg.tmp"

echo "  nagios_cfg_srcfile	$srcfile" >>$MODLOCALDB

cp "$srcfile" $outfile

# nagios.cfg: external networks
#
echo "# additional configs: externals nextworks" >>$outfile
echo "# from \::nagios.external_networks\:: = ::nagios.external_networks::" >>$outfile

for net in $(jtconf nagios.external_networks 2>/dev/null || :)
do
	echo "  adding config dir: $net"
	echo "cfg_dir=/etc/nagios3/$net" >>$outfile
	create_dir "/etc/nagios3/$net" nagios:nagios 2770

	echo -en "  generating ($net) nodes templates ...\n    "
	out="$outdir/$net-node.cfg"
	gen_template "$node_in" "$out" "" "" "$net"

	for name in $icons
	do
		echo -n "$name "
		out="$outdir/$net-node-$name.cfg"
		icon=$(jtconf nagios_images.$name)
		gen_template "$icon_in" "$out" "$name" "$icon" "$net"
	done
	echo
	out="$outdir/$net-auto-globals.cfg"
	gen_template "$net_in" "$out" "" "" "$net"
done
echo >>$outfile

# nagios.cfg: other (custom) config dirs
#
echo "# additional configs: custom defined" >>$outfile
echo "# from \::nagios.other_cfgdirs\:: = ::nagios.other_cfgdirs::" >>$outfile

for dir in $(jtconf nagios.other_cfgdirs 2>/dev/null || :)
do
	echo "  adding config dir: $dir"
	echo "cfg_dir=/etc/nagios3/$dir" >>$outfile
	create_dir "/etc/nagios3/$dir" nagios:nagios 2770
done
echo >>$outfile

echo >>$outfile
echo "# end-of-file" >>$outfile

exit 0
