#!/bin/sh
# chkconfig: 2345 62 38
### BEGIN INIT INFO
# Provides:          dovecot
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start dovecot at boot time
# Description:       Enable service provided by dovecot.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  62
# X-Timesys-Stop-Number:  38
### END INIT INFO

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

prog="dovecot"
PIDFILE=/var/run/${prog}/master.pid
CONFFILE=/etc/dovecot/${prog}.conf

if [ ! -f $CONFFILE ]; then
    echo "$CONFFILE not found"
    exit 1
fi

case "$1" in
  start)
    printf "Starting $prog: "

    if [ -z "$(grep ^dovecot /etc/passwd 2>/dev/null)" ]; then
        echo "$0: Creating system user 'dovecot' with generic settings.  Review and modify as required."
        yes '' | adduser dovecot >/dev/null 2>&1 || yes '' | useradd dovecot >/dev/null 2>&1
    fi

    if [ -z "$(grep ^dovenull /etc/passwd 2>/dev/null)" ]; then
        echo "$0: Creating system user 'dovenull' with generic settings.  Review and modify as required."
        yes '' | adduser dovenull >/dev/null 2>&1 || yes '' | useradd dovenull >/dev/null 2>&1
    fi

    ${prog}

    if [ $? == 0 ]; then
        echo "[ OK ]"
    else
        echo "[ FAIL ]"
    fi
    ;;
  stop)
    printf "Shutting down $prog: "

    if [  -r $PIDFILE  -a  ! -z ${PIDFILE}  ]; then
        PID=`cat ${PIDFILE}`
    fi
    if [  ${PID:=0} -gt 1 -a  ! "X$PID" = "X "  ]; then
        kill ${PID}
        echo "[ OK ]"
    else
        echo "[ Unable to read PID file ]"
    fi

    ;;
  restart)
        $0 stop
        $0 start
        ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

