#!/bin/sh -e
#
# make_aliases
# $Id$
# Copyright (C) 2000-2002  Dmitry V. Levin <ldv@altlinux.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

: ${TEMPLATE=/usr/share/sendmail-common/aliases}
: ${ALIASES=/etc/aliases}
: ${NOUSER=unknown-mail-user}

PASSWD=/etc/passwd

exit_handler()
{
	local rc=$?
	trap '' EXIT
	[ -z "$TMPFILE" ] || rm -f "$TMPFILE"
	exit $rc
}

if [ -z "$1" ]; then
	TMPFILE="$(mktemp -t -- "aliases.XXXXXXXX")"
	trap exit_handler SIGHUP SIGPIPE SIGINT SIGTERM EXIT
	NEEDCAT=1
else
	TMPFILE="$1"
	NEEDCAT=
fi

# Truncate
:>"$TMPFILE"

# Basic system aliases
cat "$TEMPLATE" |while read; do
	if echo "$REPLY" |egrep -qs '^[^#]*:'; then
		n=`echo "$REPLY" |cut -d: -f1`
		if v=`grep -s "^$n:" "$ALIASES"` && [ "$v" != "$REPLY" ]; then
			p="$v"
		else
			p="$REPLY"
		fi
	else
		p="$REPLY"
	fi
	echo "$p" >>"$TMPFILE"
done

UID_MIN=`grep -s ^UID_MIN /etc/login.defs |head -1 |awk '{print $2}'`
[ -n "$UID_MIN" ] || UID_MIN=500

echo -e "\n# General redirections for pseudo accounts." >>"$TMPFILE"

awk -F: -v "uid_min=$UID_MIN" '{if ($3<uid_min) print $1}' <"$PASSWD" |egrep -v '^(root|postmaster)$' |while read; do
	h=`grep "^$REPLY:" /etc/passwd |cut -d: -f6`
	if [ -n "$h" ] && [ -s "$h/.forward" -o -s "$h/.procmailrc" ]; then
		continue
	fi
	if v=`grep -s "^$REPLY:" "$ALIASES"` && [ "$v" != "$REPLY" ]; then
		p="$v"
	else
		p="$REPLY:	unknown-mail-user"
	fi
	echo "$p" >>"$TMPFILE"
done

echo -e "\n# Person who should get root's mail." >>"$TMPFILE"

r=`grep -s '^root:' "$ALIASES" |head -1`
if [ -n "$r" ]; then
	p="$r"
else
	r=`awk -F: -v "uid_min=$UID_MIN" '{if ($3>=uid_min){print $1;exit}}' <"$PASSWD" |egrep -v '^(root|postmaster)$'`
	if [ -n "$r" ]; then
		p="root:	$r"
	else
		p=
	fi
fi
if [ -n "$p" ]; then
	echo "$p" >>"$TMPFILE"
fi

echo -e "\n# Local system aliases" >>"$TMPFILE"

if [ -s "$ALIASES" ]; then
	cat "$ALIASES" |while read; do
		t="$(echo -n "$REPLY" |sed -e 's/^\(#.*\) Postfix/\1 MTA/;s/\([\\^$*.]\|\[\|\]\)/\\&/g')"
		if ! grep -qs "^$t\$" "$TMPFILE"; then
			echo "$REPLY" >>"$TMPFILE"
		fi
	done
fi

[ -z "$NEEDCAT" ] || cat "$TMPFILE"
