#!/bin/sh -e
#
# Debian package postinst
# Version 1.2
#
# Robert Leslie <rob@mars.org>

case "$1" in
    configure)
	# continue below
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
	exit 0
    ;;

    *)
	echo "postinst called with unknown argument \`$1'" >&2
	exit 0
    ;;
esac

if [ ! -d /etc/mail ]
then
    mkdir /etc/mail
    chown 0.0 /etc/mail
    chmod 755 /etc/mail
fi

if [ ! -d /var/spool/mqueue ]
then
    mkdir /var/spool/mqueue
    chown 0.0 /var/spool/mqueue
    chmod 700 /var/spool/mqueue
fi

if [ ! -f /var/log/sendmail.st ]
then
    touch /var/log/sendmail.st
    chown 0.0 /var/log/sendmail.st
    chmod 644 /var/log/sendmail.st
fi

update-rc.d sendmail defaults >/dev/null
update-inetd --disable smtp

# Move old configuration files to their new home

if [ -f /etc/sendmail.cf -a  \
    ! -L /etc/sendmail.cf -a  \
    ! -f /etc/mail/sendmail.cf ]
then
    echo "This version of the Debian sendmail package keeps its configuration"
    echo "files under /etc/mail. You already have some sendmail configuration"
    echo -n "files in /etc; would you like to move them to /etc/mail? [Y] "
    read yn
    test -n "$yn" || yn="Y"

    case "$yn" in
	[Yy]*)
	    echo "Moving /etc/sendmail.* to /etc/mail ..."
	    mv -f /etc/sendmail.* /etc/mail/.

	    test ! -f /etc/mail/sendmail.cf ||  \
		mv -f /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old
	;;

	*)
	    echo "Okay, leaving them where they are; they won't be used."
	;;
    esac
fi

# Make sure /etc/sendmail.cf points to /etc/mail/sendmail.cf

if [ -e /etc/sendmail.cf ]
then
    if [ -L /etc/sendmail.cf ]
    then
	rm -f /etc/sendmail.cf
    else
	echo "Saving old /etc/sendmail.cf as /etc/sendmail.cf.old ..."
	mv -f /etc/sendmail.cf /etc/sendmail.cf.old
    fi
fi

ln -s mail/sendmail.cf /etc/sendmail.cf

# Check existing /etc/mail/sendmail.cf

if [ -f /etc/mail/sendmail.cf ]
then
    if [ 8.8.5 = "$(sed -n -e '/^DZ/s/^DZ//p' /etc/mail/sendmail.cf)" ]
    then
	echo "Existing /etc/mail/sendmail.cf found, and it appears it may be"
	echo -n "compatible with this version of sendmail. Use it? [Y] "
	read yn
	test -n "$yn" || yn="Y"
    else
	echo "Existing /etc/mail/sendmail.cf found, but it is probably not"
	echo -n "compatible with this version of sendmail. Use it anyway? [N] "
	read yn
	test -n "$yn" || yn="N"
    fi

    case "$yn" in
	[Yy]*)
	;;

	*)
	    echo "Saving old /etc/mail/sendmail.cf"  \
		"as /etc/mail/sendmail.cf.old ..."
	    mv -f /etc/mail/sendmail.cf /etc/mail/sendmail.cf.old
	;;
    esac
fi

test -f /etc/mail/sendmail.cf || sendmailconfig --no-reload

# Start server

echo -n "Start sendmail now? [Y] "
read yn
test -n "$yn" || yn="Y"

case "$yn" in
    [Nn]*)
	echo "Not started; to start later, do: /etc/init.d/sendmail start"
	echo -n "Press [ENTER] "
	read line
    ;;

    *)
	/etc/init.d/sendmail start
    ;;
esac
