#!/bin/sh

### BEGIN INIT INFO
# Provides:        mtpolicyd
# Required-Start:  $network $local_fs $remote_fs $syslog $named $time
# Required-Stop:   $network $local_fs $remote_fs $syslog $named
# Should-Start:    memcached
# Should-Stop:     memcached
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# X-Start-Before:  postfix
# X-Stop-After:    postfix
# Short-Description: mtpolicyd Postfix policy daemon
# Description:       mtpolicyd is a modular policyd for postfix
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin

. /lib/lsb/init-functions

pathfind() {
  OLDIFS="$IFS"
  IFS=:
  for p in $PATH; do
    if [ -x "$p/$*" ]; then
      IFS="$OLDIFS"
      return 0
    fi
  done
  IFS="$OLDIFS"
  return 1
}

DAEMON=/usr/bin/mtpolicyd
PIDDIR=/var/run/mtpolicyd
PIDFILE=$PIDDIR/mtpolicyd.pid
RUNASUSER=mtpolicyd

test -x $DAEMON || exit 5

if [ -r /etc/default/mtpolicyd ]; then
	. /etc/default/mtpolicyd
fi

case $1 in
	start)
                # Create the run directory if it doesn't exist since it may be on a tmpfs
                if [ ! -d "$PIDDIR" ]; then
                install -o "$RUNUSER" -g "$RUNASUSER" -m 755 -d "$PIDDIR" || exit 2
                # For SE Linux
                    if pathfind restorecon; then restorecon "$PIDDIR"
                    fi
                fi
		log_daemon_msg "Starting postfix policy server" "mtpolicyd"
  		start-stop-daemon \
			--start --quiet \
			--oknodo --pidfile $PIDFILE --startas $DAEMON
		status=$?
		log_end_msg $status
  		;;
	stop)
		log_daemon_msg "Stopping postfix policy server" "mtpolicyd"
  		start-stop-daemon \
			--stop --quiet \
			--oknodo --pidfile $PIDFILE
		log_end_msg $?
		rm -f $PIDFILE
  		;;
	restart|force-reload)
		$0 stop && sleep 2 && $0 start
  		;;
	try-restart)
		if $0 status >/dev/null; then
			$0 restart
		else
			exit 0
		fi
		;;
	reload)
		exit 3
		;;
	status)
		status_of_proc $DAEMON "mtpolicyd daemon"
		;;
	*)
		echo "Usage: $0 {start|stop|restart|try-restart|force-reload|status}"
		exit 2
		;;
esac
