#!/bin/bash
#
# /etc/rc.d/init.d/milter-manager
#
# chkconfig: 2345 80 20
# description: The milter that manages milters to combine them flexibly.
# processname: milter-manager
# config: /etc/sysconfig/milter-manager
# pidfile: /var/run/milter-manager/milter-manager.pid
#
### BEGIN INIT INFO
# Provides:          milter-manager
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: milter manager's init script
# Description:       The milter that manages milters to combine them flexibly.
### END INIT INFO

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

name="milter manager"
prog="milter-manager"
milter_manager=/usr/sbin/milter-manager
USER=
GROUP=
SOCKET_GROUP=
PIDFILE=
CONNECTION_SPEC=
OPTION_ARGS=""
default_pidfile=/var/run/milter-manager/milter-manager.pid

if [ -f /etc/sysconfig/milter-manager ]; then
    . /etc/sysconfig/milter-manager
fi

DAEMON_ARGS="--daemon"
if [ -n "${PIDFILE}" ]; then
    DAEMON_ARGS="${DAEMON_ARGS} --pid-file ${PIDFILE}"
fi
if [ -n "${CONNECTION_SPEC}" ]; then
    DAEMON_ARGS="${DAEMON_ARGS} --connection-spec ${CONNECTION_SPEC}"
fi
if [ -n "${USER}" ]; then
    if ! getent passwd | grep -q "^${USER}:"; then
        echo "$0: user for running $prog doesn't exist: ${USER}" >&2
        exit 1
    fi
    if [ -n "${PIDFILE}" ]; then
        mkdir -p `dirname ${PIDFILE}`
        chown -R ${USER} `dirname ${PIDFILE}`
    fi
    DAEMON_ARGS="${DAEMON_ARGS} --user-name ${USER}"
fi
if [ -n "${GROUP}" ]; then
    if ! getent group | grep -q "^${GROUP}:"; then
        echo "$0: group for running $prog doesn't exist: ${GROUP}" >&2
        exit 1
    fi
    DAEMON_ARGS="${DAEMON_ARGS} --group-name ${GROUP}"
fi
if [ -n "${SOCKET_GROUP}" ]; then
    if ! getent group | grep -q "^${SOCKET_GROUP}:"; then
        echo "$0: group for socket doesn't exist: ${SOCKET_GROUP}" >&2
        exit 1
    fi
    DAEMON_ARGS="${DAEMON_ARGS} --unix-socket-group ${SOCKET_GROUP}"
fi
DAEMON_ARGS="${DAEMON_ARGS} ${OPTION_ARGS}"

killproc_options=
if [ -n "${PIDFILE}" ]; then
    killproc_options="-p ${PIDFILE}"
else
    killproc_options="-p ${default_pidfile}"
fi

RETVAL=0


start() {
    echo -n "Starting $name: "
    daemon $milter_manager "$DAEMON_ARGS"
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog
    return $RETVAL
}

stop() {
    echo -n "Shutting down $name: "
    killproc ${killproc_options} $prog
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog
    return $RETVAL
}

restart() {
    stop
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    reload)
        killproc ${killproc_options} $prog -HUP
        ;;
    condrestart)
        [ -f /var/lock/subsys/$prog ] && restart || :
        ;;
    status)
        status $prog
        ;;
    *)
        echo "Usage: $prog {start|stop|reload|restart|condrestart}"
        exit 1
        ;;
esac
exit $?
