#!/bin/sh
#
# chkconfig: 345 55 45
# description: Allows communication with vmailmgrd using unix domain sockets.
#

# 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/bin/unixserver ] || exit 0

vmailmgrd_start(){
    # Start daemon.
    echo -n "Starting vmailmgrd: "
    EH=`ps axww | grep "/usr/sbin/vmailmgrd" | grep -v grep`
    if [ -z "$EH" ]; then
	SOCKET_FILE=`cat /etc/vmailmgr/socket-file`
	rm -f $SOCKET_FILE
	/usr/bin/unixserver $SOCKET_FILE /usr/sbin/vmailmgrd \
	    2>&1 | logger -p daemon.notice -t vmailmgrd &
	# no, I can't use pidof or something like that, since
	# it's being called via unixserver.
	sleep 1
	VPID=`ps axww | grep '/usr/sbin/vmailmgrd' | grep -v grep | awk '{print $1}'`
	if [ ! -z $VPID ]; then
	    success
	    echo
	    touch /var/lock/subsys/vmailmgrd
	else
	    failure
	    echo
	fi
    else
	echo -n "Already running."
	failure
	echo
    fi
}

vmailmgrd_stop(){
    # Stop daemon.
    echo -n "Shutting down vmailmgrd: "
    if [ -f /var/lock/subsys/vmailmgrd ]; then
	VPID=`ps axww | grep '/usr/sbin/vmailmgrd' | grep -v grep | awk '{print $1}'`
	if [ ! -z "$VPID" ]; then
	    kill $VPID && success || failure
	else
	    echo -n "Not running"
	    failure
	fi
	rm -f /var/lock/subsys/vmailmgrd
    else
	echo -n "Not running"
	failure
    fi
    echo
}

vmailmgrd_restart(){
    # Restart daemon.
    if [ -f /var/lock/subsys/vmailmgrd ]; then
	vmailmgrd_stop
	sleep 1
    fi
    vmailmgrd_start
}

# See how we were called.
case "$1" in
  start)
	vmailmgrd_start
	;;
  stop)
	vmailmgrd_stop
	;;
  restart)
	vmailmgrd_restart
        ;;
  *)
	echo "Usage: vmailmgrd {start|stop|restart}"
	exit 1
esac

exit 0
