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

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

# Source networking configuration.
# Check that networking is up.
SourceIfNotEmpty /etc/sysconfig/network && [ "$NETWORKING" != no ] || exit

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

UID_MIN=`grep -s ^UID_MIN /etc/login.defs |head -1 |awk '{print $2}'`
[ -n "$UID_MIN" ] || UID_MIN=500
NON_SYSTEM_USERS=`awk -F: -v "uid_min=$UID_MIN" '{if ($3>=uid_min) print $1}' </etc/passwd`

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

start()
{
	if [ "$BOOTUP" != verbose ]; then
		INITLOG_ARGS=-q
	else
		INITLOG_ARGS=
	fi

	for fuser in $NON_SYSTEM_USERS; do
		local HOME_DIRECTORY=`awk -F: -v fuser="$fuser" '{if ($1 == fuser) print $6}' </etc/passwd`
		[ -n "$HOME_DIRECTORY" ] || continue
		if grep -qs '^ *set daemon' "$HOME_DIRECTORY/.fetchmailrc"; then
			echo -n "Starting Fetchmail service for $fuser: "
			initlog $INITLOG_ARGS -c \
			    "su -s /bin/sh -l $fuser -c 'fetchmail -f "$HOME_DIRECTORY/.fetchmailrc" &'" 
			RETVAL=$?
			[ $RETVAL -eq 0 ] && success "startup for $fuser" || failure "startup for $fuser"
			echo
			[ $RETVAL -eq 0 ] && touch "$LOCKFILE"
		fi
	done

	if [ -s /etc/fetchmailrc ]; then
		echo -n "Starting Fetchmail service with global config: "
    		initlog $INITLOG_ARGS -c \
			"su -s /bin/sh -l fetchmail -c 'fetchmail -f /etc/fetchmailrc --nopermcheck &'"
		RETVAL=$?
		[ $RETVAL -eq 0 ] && success "startup with global config" || failure "startup with global config"
		echo
		[ $RETVAL -eq 0 ] && touch "$LOCKFILE"
	fi

	return $RETVAL
}

stop()
{
	echo -n "Shutting Fetchmail services: "
	killproc fetchmail
	RETVAL=$?
	echo
	rm -f "$LOCKFILE"
	return $RETVAL
}

reload()
{
	echo -n "Reloading Fetchmail configuration: "
	killproc fetchmail -USR1
	RETVAL=$?
	echo
	return $RETVAL
}

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
