#!/bin/bash

# groundskeeper - run the argument later, when the computer isn't too
# busy, and only if it really needs doing. 

# Designed to make cron more useful for computers that aren't on all
# the time, and to replace run-parts in Red Hat (5.1)'s standard
# /etc/crontab for running daily, weekly, and monthly scripts
# in directories.

# i.e. if you want the jobs in /etc/cron.daily done daily,
# but don't keep the computer on all day, have cron hourly run
# "groundskeeper 1 /etc/cron.daily"

# example /etc/crontab:
#SHELL=/bin/bash
#PATH=/sbin:/bin:/usr/sbin:/usr/bin
#MAILTO=root
#
## run-parts
#01 * * * * root run-parts /etc/cron.hourly
#01 * * * * root /usr/local/bin/groundskeeper 1 /etc/cron.daily
#01 * * * * root /usr/local/bin/groundskeeper 7 /etc/cron.weekly
#01 * * * * root /usr/local/bin/groundskeeper 30 /etc/cron.monthly

# with ls-F /etc/cron.* =
#cron.daily:
#logrotate*      tetex.cron*     tmpwatch*       updatedb.cron*
#
#cron.hourly:
#
#cron.monthly:
#
#cron.weekly:
#makewhatis.cron*


# keep going when something fails
set +e

if [ $# -lt 2 ]; then
    echo "Usage: groundskeeper <interval in days> <dir>"
    exit 1
fi

if [ ! -d $2 ]; then
    echo "Not a directory: $2"
    exit 1
fi

for i in $2/* ; do
    if [ -x $i ]; then
        diri=/var/spool/cron/`/usr/bin/dirname $i`
	if [ ! -d $diri ]; then
	    mkdir -p $diri
	fi
	istamp=`/bin/basename $i`.lastdone
	beendone=`find $diri -name $istamp -mtime -$1 -print`
	if [ -z $beendone ]; then
	    batch -f $i
	    touch /var/spool/cron/$i.lastdone
	fi
    fi
done

exit 0