#!/bin/sh
#
# chkconfig: 345 91 35
# description: Starts and stops the SSL-POP3 stunnel (SSL) daemon
# probe: true

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

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

[ -f /usr/sbin/stunnel ] || exit 0

certdir=/var/ssl/certs

# Extracted from 'functions' to fix a tiny bug where it uses 'pidof'
# but should be using 'pidofproc'.
status() {
	# Test syntax.
	if [ $# = 0 ] ; then
		echo "Usage: status {program}"
		return 1
	fi

	# First try "pidofproc"
	pid=`pidofproc $1`
	if [ "$pid" != "" ] && ps h $pid >/dev/null 2>&1 ; then
	        echo "$1 (pid $pid) is running..."
	        return 0
        else
		pid=`pidof -o $$ -o $PPID -o %PPID -x $1`
		if [ "$pid" != "" ] ; then
		        echo "$1 (pid $pid) is running..."
		        return 0
		fi
	fi

	# Next try "/var/run/*.pid" files
	if [ -f /var/run/$1.pid ] ; then
	        pid=`head -1 /var/run/$1.pid`
	        if [ "$pid" != "" ] ; then
	                echo "$1 dead but pid file exists"
	                return 1
	        fi
	fi

	# See if /var/lock/subsys/$1 exists
	if [ -f /var/lock/subsys/$1 ]; then
		echo "$1 dead but subsys locked"
		return 2
	fi
	echo "$1 is stopped"
	return 3
}

# Name of process, subsystem *and* tcpd-control name in /etc/hosts.{allow,deny}
SERVICE_NAME="spop3"

RETVAL=0

# See how we were called.
case "$1" in
  start)
	echo -n "Starting ssl-pop3: "

	# See if it's already running.
	pid=`pidofproc ${SERVICE_NAME}`
	[ -n "$pid" ] && ps h $pid >/dev/null 2>&1 && echo && exit $RETVAL

	daemon --check ${SERVICE_NAME} /usr/sbin/stunnel -N ${SERVICE_NAME} \
		-P /var/run/${SERVICE_NAME}.pid \
		-p $certdir/${SERVICE_NAME}_server.pem \
		-d mail.timecastle.net:spop3 -r localhost:pop3
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/${SERVICE_NAME}
	;;
  stop)
	echo -n "Shutting down ssl-pop3: "
	killproc ${SERVICE_NAME}
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/${SERVICE_NAME}
	;;
  restart|reload)
	$0 stop
	$0 start
	RETVAL=$?
	;;

  status)
	status ${SERVICE_NAME}
	[ $RETVAL -ne 0 ] && RETVAL=$?
	;;
  probe)
	# echo command to start/restart service, only if NOT already running...
	# (this is a linuxconf convention, using the probe keyword above)
	if [ ! -f /var/lock/subsys/${SERVICE_NAME} ] ; then
		echo start; exit 0
	fi

	pid=`pidofproc ${SERVICE_NAME}`
	[ -n "$pid" ] && ps h $pid >/dev/null 2>&1 && exit $RETVAL

	echo restart; exit 0
	;;
  *)
	echo "Usage: $0 {start|stop|restart|reload|probe|status}"
	exit 1
esac

exit $RETVAL
