#!/bin/bash

set -e -u

. ${TOOLKIT}-functions.sh

#----------------------------------------------------------------
# builds /etc/rsyncd.conf
#----------------------------------------------------------------

file=rsyncd.conf
input=$(filepath "$file")
outfile="$file.tmp"
cp "$input" "$outfile"

uname=$(uname -n)				# fdqn
suname=$(echo $uname | sed -e 's/\..*//')	# strip domain

donefile="modules_done.tmp"
:>$donefile

echo -en "  $file: building modules list: "
[ "X$(jtconf --list rsync.module.)" = "X" ] && {
	echo "(no modules)"
	exit 0
}

optionsfile="options-list"

for module in $(jtconf --list rsync.module. | sort)
do
	modulename=$(echo $module | sed -e 's/rsync\.module\.//')

	grep -q "^$modulename$" $donefile && {
		putwarning "rsync" "ignoring module '$modulename' duplicated"
		continue
	}

	# 'server' defined and not this?
	#
	server=$(jtconf $module.server 2>/dev/null) && {
		[ "$server" = $uname -o "$server" = $suname ] || continue
			echo -e "\n# module for machine: $server" >>$outfile
	}

	echo -en "$modulename "

	echo -e "\n[$modulename]" >>$outfile

	for var in $(jtconf --listvars $module)
	do
		[ "$var" = "server" ] && continue
		rsyncvar=$(echo $var | sed -e 's/_/ /g')
		grep -q "^$rsyncvar$" $optionsfile || {
			echo "error, unknown rsync directive '$rsyncvar'" >&2
			exit 1
		}
		val=$(jtconf $module.$var)
		[ "X$val" = "X" ] && continue

		echo "  $rsyncvar = $val" >>$outfile
	done
done
echo "(ok)"


customfile=$(filepath "custom-$file") || :

if [ "X$customfile" != "X" ]
then
	echo -e "\n  $file: adding custom file '$customfile'\n"
	echo >>"$outfile"
	echo "# customfile: $customfile" >>"$outfile"
	echo >>"$outfile"
	cat "$customfile" >>"$outfile"
	echo >>"$outfile"
	echo "# customfile: $customfile EOF" >>"$outfile"
else
	echo -e "\n  $file: custom file 'custom-$file' not fond, skipped\n"
fi

echo "
# /etc/$file EOF" >>"$outfile"


exit 0
