#!/bin/sh
#
# Pre/post-installation setup of ravsendmail

PATH=/bin:/usr/bin:/sbin:/usr/sbin
PREFIX="/usr/local"
RAVSENDMAIL="${PREFIX}/bin/ravsendmail"

generic_which()
{
  b=false
  IFS=:
  for d in $PATH; do
    if [ -x $d/$1 ]; then
      b=$d/$1
    fi
  done
  echo $b
}

# Function: create the sendmail configuration file
#
do_activate()
{
	#create the sendmail configuration files
	if [ -f  /etc/mail/sendmail.cf ]; then
		sendmail_cf=/etc/mail/sendmail.cf
	else
		if [ -f /etc/sendmail.cf ]; then
			sendmail_cf=/etc/sendmail.cf
		else
			sendmail_cf=false
			echo "| Could not locate sendmail.cf."
			echo "| You have to create manually the sendmail"
			echo "| configuration file. Please read the INSTALL"
			echo "| file for more information."
		fi
	fi
	if [ "$sendmail_cf" != "false" ]; then
		echo "-> Adding RAV settings to the sendmail configuration file ..."
		ex=`(generic_which ex)`
		if [ ! -f $sendmail_cf.rav ]; then 
			cp $sendmail_cf $sendmail_cf.rav
		fi
		cp $sendmail_cf $sendmail_cf.orig

$ex $sendmail_cf >/dev/null <<EOF
/^Sparse=0/,/^SParse0/s/\$: \$>Parse1 \$1.*/\$#ravsendmail \$@\$1 \$:\$1/
/^S0/,/^SParse0/s/\$: \$>Parse1 \$1.*/\$#ravsendmail \$@\$1 \$:\$1/
/^Msmtp,/
i
#rav-begin: RAV Configuration
Mravsendmail,   P=${RAVSENDMAIL}, F=ClADFMSPhu, S=0, R=0,
                T=DNS/RFC822/X-Unix,
                A=ravsendmail /var/rav \$h \$f \$u \$i
#rav-end
. 
x!
EOF

$ex $sendmail_cf.orig >/dev/null <<EOF
1,\$s/^O QueueDirectory/# &/
/QueueDirectory/
a
#rav-begin-1: RAV Configuration
O QueueDirectory=/var/rav/tmp
#rav-end-1
.
1,\$s/^O StatusFile/# &/
/StatusFile/
a
#rav-begin-2: RAV Configuration
O StatusFile=/var/log/sendmail.st.orig
#rav-end-2
.
1,\$s/^O PidFile/# &/
/PidFile/
a
#rav-begin-3: RAV Configuration
O PidFile=/var/run/sendmail.pid.orig
#rav-end-3
.
x!
EOF

		echo "-> Reloading sendmail configuration ..."
		killall -HUP sendmail 2>/dev/null

		echo "-> Starting the second sendmail executable ..."
		if [ ! -f /usr/sbin/sendmail.orig ]; then
			cp -f /usr/sbin/sendmail /usr/sbin/sendmail.orig 2>/dev/null
		fi
		/usr/sbin/sendmail.orig -C ${sendmail_cf}.orig -q5m 2>/dev/null
	fi
}

# verify proper execution
#
if [ $# -ne 2 ]; then
	echo "usage: $0 distname { PRE-INSTALL | POST-INSTALL }" >&2
	exit 1
fi

# Verify/process the command
#
case $2 in
	PRE-INSTALL)
	;;
	POST-INSTALL)
	do_activate
	echo ""
	;;
	*)
	echo "Usage: `basename $0` distname <PRE-INSTALL|POST-INSTALL>" >&2
	exit 1
	;;
esac

exit 0
