#!/bin/sh
# Startup script for anacron
#
# chkconfig: 2345 99 05
# description: Run cron jobs that were left out due to downtime
# pidfile: /var/run/anacron.pid
#
# Source function library.
. /etc/rc.d/init.d/functions

[ -f /usr/sbin/anacron ] || exit 0

prog="anacron"
PIDFILE=/var/spool/anacron/cron.daily
LOCKFILE=/var/lock/subsys/$prog
#
#  NOTE: anacron exits after it has determined it has no more work to do.
#        Hence, its initscript cannot do normal lock file management.
#        The anacron binary now creates its own timestamps in files 
#	 /var/spool/anacron/cron.{daily,monthly,weekly}
#        and /var/lock/subsys lock files. 
#

start() {
    echo -n $"Starting $prog: " 
# on_ac_power doesn't exist, on_ac_power returns 0 (ac power being used)
    if test -x /usr/bin/on_ac_power
	then
	/usr/bin/on_ac_power > /dev/null
        if test $? -eq 1
	    then
		echo "deferred while on battery power."
	        RETVAL=0
	    exit 0
        fi
    fi

# If starting within 15 minutes of midnight or before 5 am, defer until
# the scheduled 5am anacron run -- this allows the regular cron jobs to
# run first, so that anacron doesn't repeat jobs that the regular cron
# job will pick up as well.

    if [ `date +%H -d "15 minutes"` -le 4 ] ; then
        echo "deferred until after the regular morning cron job run"
        exit 0
    fi
 
    daemon +19 anacron -s
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
	failure;
    fi;
    echo
}

stop() {
    echo -n $"Stopping $prog: "
    if [ -f $PIDFILE ]; then
	killproc anacron
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then 
	    failure;
	fi;
    else
	failure;
    fi
    echo
}

case "$1" in
	start)
	    start
	    ;;
	
	stop)
	    stop
	    ;;
	
	status)
	    ## hard to say - anacron is up only when cron wake him
	    status $prog
	    RETVAL=$?
	    ;;

	restart)
	    stop
	    start
	    ;;

	condrestart)
		if [ -f /var/lock/subsys/anacron ]; then
			stop
			sleep 2
			start
		fi
		;;

	*)
	    echo $"Usage: $0 {start|stop|restart|condrestart|status}"
	    RETVAL=3

esac

exit $RETVAL
