#!/bin/sh -e
#
# make_aliases
# $Id: make_aliases,v 1.2 2003/10/19 13:50:52 ldv Exp $
# Copyright (C) 2000-2003  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
#

: ${ALIASES_TEMPLATE:=/usr/share/sendmail-common/aliases}

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
	WORKFILE="$TMPFILE"
else
	TMPFILE=
	WORKFILE="$1"
	:>"$WORKFILE"
fi

# Basic system aliases
cat "$ALIASES_TEMPLATE" |while read alias; do
	if echo "$alias" |egrep -qs '^[^#]*:'; then
		name=`echo "$alias" |cut -d: -f1`
		if v=`getent aliases "$name"`; then
			p="$v"
		else
			p="$alias"
		fi
	else
		p="$alias"
	fi
	echo "$p" >>"$WORKFILE"
done

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

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

r=`getent aliases root |head -1`
if [ -n "$r" ]; then
	p="$r"
else
	r=`getent passwd |awk -F: -v "uid_min=$UID_MIN" '{if ($3>=uid_min){print $1;exit}}' |egrep -v '^(root|postmaster)$'`
	if [ -n "$r" ]; then
		p="root:           $r"
	else
		p=
	fi
fi
if [ -n "$p" ]; then
	echo "$p" >>"$WORKFILE"
fi

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

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

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