#!/bin/sh
#
# chkconfig: 235 91 10
# description:	Starts and stops the fetchmail daemon used to retrieve mail \
#		via various protocols (such as POP3 and IMAP4).
#
# config:	/etc/fetchmailrc
#
### BEGIN INIT INFO
# Provides: fetchmail
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 3 4 5
# Short-Description: The fetchmail mail retrieving daemon
# Description: Starts and stops the fetchmail daemon used to retrieve mail \
#              via various protocols (such as POP3 and IMAP4).
### END INIT INFO

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

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ $NETWORKING = "no" ] && exit 0

# Source fetchmail configuration.
if [ -s /etc/sysconfig/fetchmail ]; then
    . /etc/sysconfig/fetchmail
else
    echo "Configuration file not found "
    exit 0
fi

CONFFILE="/etc/fetchmailrc"
HOMEDIR="/var/run/fetchmail"
PIDFILE="$HOMEDIR/.fetchmail.pid"
UIDL="$HOMEDIR/.fetchmail-UIDL-cache"
OPTIONS="-s -d ${POLL:-180} -f $CONFFILE --pidfile $PIDFILE"
RETVAL=0

# Check that fetchmailrc exists.
[ -s $CONFFILE ] || exit 0

# Check that group exists
if ! grep -qs $USER /etc/group; then
    echo "Adding $USER group "
    groupadd -g 200 $USER
fi

# Check that user exists.
if ! grep -qs $USER /etc/passwd; then
    echo "Adding $USER user "
    useradd -u 200 -g $USER -d $HOMEDIR  -s /sbin/nologin $USER
fi

# create uidl cache file
if ! grep -qs idfile "$CONFFILE" && [ -d $HOMEDIR ]; then 
    OPTIONS="$OPTIONS -i $UIDL"
    touch $UIDL
    chown -h $USER $UIDL
    chmod 0600 $UIDL
fi

# See how we were called.
case "$1" in
    start)
	if [ ! -f /var/lock/subsys/fetchmail ]; then
	    echo -n "Starting Fetchmail services: "
	    daemon --user=$USER /usr/bin/fetchmail $OPTIONS
	    RETVAL=$?
	    echo
	    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/fetchmail
	else
	    RETVAL=1
	fi
        ;;
    stop)
	if [ -f /var/lock/subsys/fetchmail ]; then
	    action "Shutting Fetchmail services: " su -l $USER -c '/usr/bin/fetchmail -s --quit'
	    rm -f /var/lock/subsys/fetchmail >/dev/null 2>&1
	    RETVAL=$?
	else
	    RETVAL=1
	fi
        ;;
    restart)
	$0 stop
	$0 start
	RETVAL=$?
	;;
    reload)
	if [ -f /var/lock/subsys/fetchmail ]; then
	    echo -n "Reloading fetchmailrc file: "
	    killproc fetchmail -HUP
	    RETVAL=$?
	    echo
	else
	    RETVAL=1
	fi
	;;
    status)
	status fetchmail
	RETVAL=$?
	;;
    *)
	echo "Usage: $0 {start|stop|restart|reload|status}"
	exit 1
esac

exit $RETVAL
