#!/bin/sh

### BEGIN INIT INFO
# Provides:
# Required-Start:
# Default-Start: 3 4 5
# Default-Stop: 0 1 2
# Description: Cyrus IMAP
### END INIT INFO

NAME=cyrus
DAEMON=/usr/cyrus/bin/master
LD_LIBRARY_PATH=/usr/cyrus-sasl2/lib:/usr/cyrus-sasl/lib/sasl:/usr/lib:/lib
SASL_PATH=/usr/cyrus-sasl2/lib/sasl2
export LD_LIBRARY_PATH
export SASL_PATH

tmpfile=/tmp/pid.$$

ps -aef > $tmpfile

cleanup() {
	rm -f $tmpfile
	exit $1
}

[ -f /usr/cyrus/bin/master ] || cleanup 5

case "$1" in
 start)
  if grep -q "/usr/cyrus/bin/master" $tmpfile 
  then
	echo "Cyrus master daemon already running."
  else
			# up the file descriptors for up to 5000 clients
			if [ -f /proc/sys/fs/file-max ]
			then
				files=`cat /proc/sys/fs/file-max`
				if [ $files -lt 150000 ]
				then
					echo 150000 > /proc/sys/fs/file-max
				fi
				unset files
			fi
	echo "Starting Cyrus master daemon."
	# for now, we have our own cyrus library
	cd /var/run
	/usr/cyrus/bin/master -l 256 &
	ret=$?
  fi

  ;;

 stop)

	pid=`grep "/usr/cyrus/bin/master" $tmpfile | awk '{print $2}'`
	ps -eaf >$tmpfile
	if [ -n "$pid" ]; then
		echo "Shutting down cyrus master daemon."
		kill -9 $pid >/dev/null
		# now kill all the imapd's
		ps -e | egrep '(imapd|pop3d)' | awk '{print $1}' > /tmp/imapkill$$

		for i in `cat /tmp/imapkill$$`
		do
			kill $i
		done

		rm -f /tmp/imapkill$$
	else
		echo "Cyrus master daemon is not running."
	fi
  ret=0

  ;;

 force-reload|reload)

  echo "Reloading cyrus configuration files: "
  ret=$?
  echo "done."
  ;;

 restart)
  $0 stop
  $0 start
  ret=$?
  ;;

 status)
  ret=3
  ;;

 *)
  echo "Usage: cyrus {[re]start|stop|[force-]reload|status}"
  ret=2
  ;;

esac

cleanup $ret
