#!/bin/bash
#
# exim    This shell script takes care of starting and stopping exim
#
# chkconfig: 2345 80 30
# description: Exim is a Mail Transport Agent, which is the program \
#              that moves mail from one machine to another.
# processname: exim
# config: /etc/exim/exim.conf
# pidfile: /var/run/exim.pid

# Source function library.
. /etc/init.d/functions

# Source networking configuration.
[ -r /etc/sysconfig/network ] && . /etc/sysconfig/network

# Source exim configureation.
if [ -f /etc/sysconfig/exim ] ; then
	. /etc/sysconfig/exim
else
	DAEMON=yes
	QUEUE=1h
fi

USER=${USER:=exim}
GROUP=${GROUP:=exim}

gen_cert() {
	if [ ! -f /etc/pki/tls/certs/exim.pem ] ; then
		umask 077
		FQDN=`hostname`
		if [ "x${FQDN}" = "x" ]; then
			FQDN=localhost.localdomain
		fi
		echo -n $"Generating exim certificate: "
		cat << EOF | openssl req -new -x509 -days 365 -nodes \
			-out /etc/pki/tls/certs/exim.pem \
			-keyout /etc/pki/tls/private/exim.pem &>/dev/null
--
SomeState
SomeCity
SomeOrganization
SomeOrganizationalUnit
${FQDN}
root@${FQDN}
EOF
		if [ $? -eq 0 ]; then
			success
			chown $USER:$GROUP /etc/pki/tls/{private,certs}/exim.pem
			chmod 600 /etc/pki/tls/{private,certs}/exim.pem
		else
			failure
		fi
		echo
	fi
}

start() {
	[ "$EUID" != "0" ] && exit 4
	[ "${NETWORKING}" = "no" ] && exit 1
	[ -f /usr/sbin/exim ] || exit 5

	# check ownerships
	# do this by seeing if /var/log/exim/main.log exists and is
	# owned by exim - if owned by someone else we fix it up
	if [ -f /var/log/exim/main.log ]
	then
	    if [ "exim" != "`ls -l /var/log/exim/main.log | awk '{print $4}'`" ]
	    then
		chown -R $USER:$GROUP /var/log/exim /var/spool/exim
	    fi
	fi

	# generate certificate if doesn't exist
	gen_cert

        # Start daemons.
        echo -n $"Starting exim: "
        daemon /usr/sbin/exim $([ "$DAEMON" = yes ] && echo -bd) \
                              $([ -n "$QUEUE" ] && echo -q$QUEUE)
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch /var/lock/subsys/exim
}

stop() {
	[ "$EUID" != "0" ] && exit 4
        # Stop daemons.
        echo -n $"Shutting down exim: "
        killproc exim
	RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/exim
}

restart() {
	stop
	start
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	restart
	;;
  reload|force-reload)
	status exim > /dev/null || exit 7
	echo -n $"Reloading exim:"
	killproc exim -HUP
	echo
	;;
  condrestart|try-restart)
	status exim > /dev/null || exit 0
	restart
	;;
  status)
	status exim
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|reload|force-reload|status|condrestart|try-restart}"
	exit 2
esac

exit $RETVAL

