#!/bin/bash

. ${TOOLKIT}-functions.sh

includefile()
{
	echo "" >>$tmpfile
	echo "# ---------------------------------------------------------" >>$tmpfile
	echo "# include: '$1'" >>$tmpfile
	echo "# ---------------------------------------------------------" >>$tmpfile
	echo >>$tmpfile
	cat "$1" >>$tmpfile
	echo >>$tmpfile
	echo "# ---------------------------------------------------------" >>$tmpfile
	echo "# end include: '$1'" >>$tmpfile
	echo "# ---------------------------------------------------------" >>$tmpfile
	echo >>$tmpfile
	return 0
}


# rebuild mail aliases file (/etc/aliases)
#
aliases_file="/etc/aliases"
tmpfile="aliases.tmp"

[ -f $aliases_file ] || exit 0

cp /dev/null $tmpfile

BLOCK_START="DO NOT EDIT BLOCK BELOW -- ADDED BY KUSA"
BLOCK_END="END OF AUTOGENERATED BLOCK -- KUSA"

# remove kusa block and double empty lines
#
skip=false
skip_nl=false

old_format=false
fgrep -q "# added by kusa for root entry" /etc/aliases && old_format=true

cat /etc/aliases | while read line
do
    case $line in
      "") ;;
      *)  skip_nl=false ;;
    esac

    [ "X$line" = "X# $BLOCK_START" ]	&& { skip=true; continue; }
    [ "X$line" = "X# $BLOCK_END" ]	&& { skip=false; continue; }

    $skip && continue

    [ "X$line" = "X" ] && {
	$skip_nl && continue
	# first occurence, retain but skip the next
      	skip_nl=true
    }
 
    # clean up old format entries?
    $old_format && {
      case $line in
	"# added by kusa for root entry")	continue ;;
	root:*|postmaster:*|kusa:*)		continue ;;
	webmaster:*|www-data:*|cliadmin:*)	continue ;;
	sysadmin:*)				continue ;;
      esac
    }

    echo "$line"
done >>$tmpfile


# recreate kusa block
#
echo "# $BLOCK_START" >>$tmpfile


# standard aliases
#
std_aliases=$(filepath std_aliases)
includefile "$std_aliases"


# local aliases
#
localfile="/etc/postfix/aliases-local"

[ -f $localfile ] && {
	includefile "$localfile"
}

echo "# =============================================================" >>$tmpfile
echo "# $BLOCK_END" >>$tmpfile



# check for conflicts
#
kusa_block=$(sed \
	-e "1,/^# $BLOCK_START/d" \
	-e "/^# $BLOCK_END/,\$d" \
	-e 's/^[ ,	][ ,	]*$//' \
	-e '/^[ ,	]*#/d' \
	-e '/^$/d' \
	$tmpfile
)
nokusa_block=$(sed \
	-e "/^# $BLOCK_START/,/^# $BLOCK_END/d" \
	-e 's/^[ ,	][ ,	]*$//' \
	-e '/^[ ,	]*#/d' \
	-e '/^$/d' \
	$tmpfile
)

err=false

for name in $(echo "$nokusa_block" | grep "^[a-zA-Z].*:" | sed -e 's/:.*//')
do
	clash=$(echo "$kusa_block" | grep "^$name:") || :
	[ "X$clash" != "X" ] && {
		echo -e "  duplicate found, $clash"
		err=true
	}
done
$err && {
	echo
	echo "error, remove clashing aliases from '/etc/aliases' and retry"
	exit 1
}


installfile $tmpfile $aliases_file root:root 664

$SOMETHING_CHANGED && {
	[ "$(which newaliases)" != "" ] && {
		echo "  running newaliases"
		newaliases
	}
}

exit 0
