#!/bin/bash
#
# ::do_not_edit::
#
# ::maintainer::
# ::copy::
#
CMD=$(basename $0)
CMDVER="1.5"
CMDSTR="$CMD v$CMDVER (2019/04)"

set -e -u



# (MAIN)

dir=virtual.d

cd $dir || exit $?

file_common="_common"		# entries added to ALL domains
file_domains="_domains"		# (optional) domain list
file_local="_local"		# (optional) local manual definitions

id_errors_file=$(mktemp /tmp/${CMD}-XXXX)

format="%-30s %s\n"


ku_sieve_cmd=$(which ku-sieve-standard-filters 2>/dev/null) || ku_sieve_cmd=":"

trap "rm -f $id_errors_file ; exit 255" 1 2 3

if [ -s $file_domains ]
then
	domains=$(cat $file_domains)
else
	domains=$(ls -d *.* 2>/dev/null)
fi

echo "
  == $CMDSTR ==
" >&2

for domain in $domains
do
	echo -en " processing $domain ... " >&2
	printf "$format" "$domain" "-------------------------------------------"
	echo ""

	files=$file_common
	[ -f $domain ] && files="$files $domain"

	sed -e 's/#.*//' -e '/^$/d' $files | while read name aliases
	do
		comma=
		formatted_aliases=
		for alias in $(echo $aliases | tr ',' ' ')
		do
			case $alias in
			  *@[a-zA-Z0-9]*)	# full address, uses as-is
			  	##echo ">>> FULL ADDRESS: $alias" >&2
			  	;;
			  *@)			# @ terminated, append current domain
			  	alias="$alias$domain"
			  	##echo ">>> @ TERMINATED ADDRESS: $alias" >&2
				;;
			  *)			# local user, must be present on system
			  	##echo ">>> LOCAL USER: $alias" >&2
				getent passwd $alias >/dev/null 2>&1 || {
					grep -q "^$alias:" /etc/aliases || {
						echo "$alias" >>$id_errors_file
						continue
					}
				}
				$ku_sieve_cmd -x $alias "$name@$domain" >/dev/null
				alias="$alias@localhost"
				;;
			esac
			formatted_aliases="$formatted_aliases$comma$alias"
			comma=","
		done
		printf "$format" "$name@$domain" "$formatted_aliases"
	done
	echo ""
	echo "ok" >&2
done



# add local file if exists
#
[ -f $file_local ] && {
	echo ""
	echo "# $file_local"
	echo ""
	cat $file_local
	echo
}

status=0

[ -s $id_errors_file ] && {
	echo -e "\nERROR! USERS NOT FOUND ON SYSTEM:\n" >&2
	sort -u $id_errors_file >&2
	echo >&2
	status=1
}

rm -f $id_errors_file
exit $status
