#!/bin/sh -e

NAME=saslauthd
DAEMON="/usr/sbin/${NAME}"
DESC="SASL Authentication Daemon"
DEFAULTS=/etc/default/saslauthd
PWDIR=/var/run/saslauthd

createdir() {
# $1 = user
# $2 = group
# $3 = permissions (octal)
# $4 = path to directory
        [ -d "$4" ] || mkdir -p "$4"
        chown -c -h "$1:$2" "$4"
        chmod -c "$3" "$4"
}

test -f "${DAEMON}" || exit 0

# Source defaults file; edit that file to configure this script.
if [ -e "${DEFAULTS}" ]; then
    . "${DEFAULTS}"
fi

# If we're not to start the daemon, simply exit
if [ "${START}" != "yes" ]; then
    exit 0
fi

# If we have no mechanisms defined
if [ "x${MECHANISMS}" = "x" ]; then
    echo "You need to configure ${DEFAULTS} with mechanisms to be used"
    exit 0
fi

# Add our mechanimsms with the necessary flag
PARAMS="${PARAMS} -a ${MECHANISMS}"

# Consider our options
case "${1}" in
  start)
        echo -n "Starting ${DESC}: "
	dir=`dpkg-statoverride --list $PWDIR`
	test -z "$dir" || createdir $dir
        start-stop-daemon --start --quiet --pidfile "/var/run/${NAME}/saslauthd.pid" --exec "${DAEMON}" -- ${PARAMS}
        echo "${NAME}."
        ;;
  stop)
        echo -n "Stopping ${DESC}: "
        start-stop-daemon --stop --quiet --pidfile "/var/run/${NAME}/saslauthd.pid" --exec "${DAEMON}" -- ${PARAMS} 
        echo "${NAME}."
        ;;
  restart|force-reload)
        echo -n "Restarting ${DESC}: "
        start-stop-daemon --stop --quiet --pidfile "/var/run/${NAME}/saslauthd.pid" --exec "${DAEMON}" -- ${PARAMS}
        sleep 1
        start-stop-daemon --start --quiet --pidfile "/var/run/${NAME}/saslauthd.pid" --exec "${DAEMON}" -- ${PARAMS}
        echo "${NAME}."
        ;;
  *)
        echo "Usage: /etc/init.d/${NAME} {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
