#!/bin/sh -e
#
# Copyright (C) 2000-2003,2006,2007  Dmitry V. Levin <ldv@altlinux.org>
#
# make_aliases
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 HUP PIPE INT TERM EXIT
	WORKFILE="$TMPFILE"
else
	TMPFILE=
	WORKFILE="$1"
	:>"$WORKFILE"
fi

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

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

printf '\n%s\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 "u=$UID_MIN" '
BEGIN {while((getline<"/etc/shells")>0) shells[$1]=1}
($3>=u && $1!="root" && $1!="postmaster" && ($7=="" || $7 in shells)) {print $1;exit}
		')"
	if [ -n "$r" ]; then
		p="root:           $r"
	else
		p='#root:           you'
	fi
fi
printf '%s\n' "$p" >>"$WORKFILE"

printf '\n%s\n'  "# Local system aliases" >>"$WORKFILE"

getent aliases |tr -s '[:blank:]' ' ' |while read alias; do
	tr -s '[:blank:]' ' ' <"$WORKFILE" |fgrep -qsx "$alias" ||
		printf '%s\n' "$alias" >>"$WORKFILE"
done

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