#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

IMAPD=/usr/sbin/dbmail-imapd
POP3D=/usr/sbin/dbmail-pop3d

IMAPD_NAME=dbmail-imapd
POP3D_NAME=dbmail-pop3d

NAME="dbmail"
DESC="dbmail servers"

test -x $IMAPD || exit 0
test -x $POP3D || exit 0

set -e

[ -e /etc/default/dbmail ] && . /etc/default/dbmail

kill_by_name() {
	NAME="$1"
	echo -n "$NAME "
	start-stop-daemon --stop --quiet --name $NAME
	i=1
	while [ "$i" -le 10 ]; do
		pidof $NAME 2>&1 >/dev/null || break
		echo -n "."
		sleep 1
		i=$(($i+1))
	done	
	pidof $NAME 2>&1 >/dev/null && killall $NAME 2>&1 >/dev/null
	
}

config_valid() {
	/usr/sbin/dbmail-adduser s 2>&1 >/dev/null && return 0
	cat << EOM
Dbmail cannot connect to the database server. Please make sure
/etc/dbmail/dbmail.conf is correct, the database-server is running,
the database for dbmail exists, and the dbmail user exists with all
necessary permissions. To re-configure /etc/dbmail/dbmail.conf run
'dpkg-reconfigure dbmail'.
EOM
	return 1
}	
ssl_wrapper() {
	# this needs more work. Use stunnel at your own risk,
	# or wait for native support for ssl in dbmail-2  :-(
	cd /etc/ssl/certs || return 0
	[ -e "$PEMFILE" ] || return 0
	[ -x /usr/sbin/stunnel ] || return 0
	# assuming stunnel runs on the same host as dbmail, even though
	# it aint necessarily so.
	STUNNLOPT="-D 6 -p $PEMFILE -S 0 -a /etc/ssl/certs -t 300 -r localhost:imap -s dbmail -g dbmail -P /var/run/"
	echo -n "SSL wrapper "
	case "$1" in 
		start)
		[ "$START_IMAPD" ] && \
			/usr/sbin/stunnel $STUNNLOPT -d imaps 
		[ "$START_POP3D" ] && \
			/usr/sbin/stunnel $STUNNLOPT -d pop3s
		;;
		
		stop)
		[ "$START_IMAPD" ] && \
			kill `cat /var/run/stunnel.localhost.imap.pid`
		[ "$START_POP3D" ] && \
			kill `cat /var/run/stunnel.localhost.pop3.pid`
		;;
	esac	
	return 0
}	

persistent_start() {
	## _debug="true"
	eval '_daemon=$'$1
	eval '_name=$'$1'_NAME'
	echo -n "$_name "
	count=0
	while [ $count -lt 30 ]; do
		echo -n "."
		start-stop-daemon --start --exec $_daemon
		sleep 2
		pids=`pidof $_daemon` 1>/dev/null
		if [ -n "$pids" ]; then
			[ $_debug ] && echo "...got pids: $pids"
			return 0
		fi	
		count=$(($count+1))
	done
	echo "Starting $_name failed."
	return 1
}


case "$1" in
  start)
	config_valid || exit 0
	echo -n "Starting $DESC: "
	[ "$START_IMAPD" ] && persistent_start "IMAPD"
	[ "$START_POP3D" ] && persistent_start "POP3D"
	[ "$START_SSL" ] && ssl_wrapper start
 	echo "done."
	;;
  stop)
	config_valid 2>&1 /dev/null || exit 0
	echo -n "Stopping $DESC: "
	[ "$START_IMAPD" ] && kill_by_name $IMAPD_NAME || true
	[ "$START_POP3D" ] && kill_by_name $POP3D_NAME || true
	[ "$START_SSL" ] && ssl_wrapper stop 2>&1 /dev/null || true
	echo "done."
	;;
  restart|force-reload)
	$0 stop || true
	sleep 3
	$0 start
	;;
  *)
	N="$NAME"
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
