#!/bin/sh
#
# chkconfig:	- 91 35
# description:	Starts and stops the fetchmail daemon used to retrive mail \
#		via various protocols (such as POP3 and IMAP4).
#
# config:	/etc/fetchmailrc

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=2

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

# until better times when localized logs are generally readable...
LC_MESSAGES=C

# Check that fetchmail exists.
[ -x /usr/bin/fetchmail ] || exit

LOCKFILE=/var/lock/subsys/fetchmail
RETVAL=0

start()
{
	UID_MIN=`grep -s ^UID_MIN /etc/login.defs |head -1 |awk '{print $2}'`
	[ -n "$UID_MIN" ] || UID_MIN=500

	IFS=:
	awk -F: -v "uid_min=$UID_MIN" \
	    '{if ($3>=uid_min) printf "%s:%s\n", $1, $6}' </etc/passwd |
	while read -r fuser HOME_DIRECTORY; do
		[ -n "$HOME_DIRECTORY" ] || continue
		unset IFS
		if grep -qs '^[ 	]*set daemon' "$HOME_DIRECTORY/.fetchmailrc"; then
			echo -n "Starting Fetchmail service for $fuser: "
			start_daemon --no-announce \
			    --user "$fuser" \
			    --pidfile "$HOME_DIRECTORY/.fetchmail.pid" \
			    --lockfile "$LOCKFILE" \
			    -- /usr/bin/fetchmail -f "$HOME_DIRECTORY/.fetchmailrc" --syslog
			RETVAL=$?
		fi
		IFS=:
	done
	unset IFS

	if grep -qs '^[ 	]*set daemon' /etc/fetchmailrc; then
		echo -n "Starting Fetchmail service with global config: "
		start_daemon --no-announce \
		    --user fetchmail \
		    --pidfile /var/run/fetchmail/fetchmail.pid \
		    --lockfile "$LOCKFILE" \
		    -- /usr/bin/fetchmail --pidfile /var/run/fetchmail/fetchmail.pid -f /etc/fetchmailrc --nopermcheck --syslog
		RETVAL=$?
	fi

	return $RETVAL
}

stop()
{
	echo -n "Stopping Fetchmail services: "
	stop_daemon --no-announce --lockfile "$LOCKFILE" /usr/bin/fetchmail
}

reload()
{
	echo -n "Reloading Fetchmail configuration: "
	stop_daemon --no-announce -USR1 /usr/bin/fetchmail
}

restart()
{
	stop
	start
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	reload)
		reload
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	status)
		status fetchmail
		RETVAL=$?
		;;
	*)
		echo "Usage: ${0##*/} {start|stop|reload|restart|condstop|condrestart|status}"
		RETVAL=1
esac

exit $RETVAL
