#!/bin/sh -e

exec 2>&1

# This is a sample service configuration for maintaining a mirror of
# multivac.cwru.edu.  It is designed for use with D. J. Bernstein's
# daemontools package from <URL:http://cr.yp.to/daemontools.html>.

# This script runs ./doit to update the local mirror every day at 2:30 AM
# local time, normally.  The script ./doit touches the file "started" when it
# starts, to record the last time it was run, and touches the file "finished"
# at the end, to record the last time it finished successfully.  (If any
# command before "touch finished" fails, the shell wil exit without running
# any further commands, because of the -e flag.)  If ./doit fails without
# touching "finished", then the statfile...rw-min sequence below ensures that
# ./doit will run again no more than 36 hours after the last time it ran
# successfully.  But even if ./doit fails repeatedly, the statfile...rw-max
# sequence ensures that it will not run more often than once per hour, to
# avoid overloading a clogged network link.

# The commands in ./doit are put in a separate script so that we can edit
# that script while rw-sleep is sleeping.  The changes will take effect for
# the next run without having to restart the service.

# In line-by-line detail, this script:
# runs as the user "mirroruser",
# puts the current time plus 1 second into $now1s,
# puts the earliest time after $now1s matching 2:30 AM into $wake
# (adding 1 second ensures that if ./doit runs in less than one second,
# rw-match won't schedule it to run again immediately; we'll schedule it for
# 2:30 AM the next day),
# puts the last-modified time of the file "finished" into $MTAI64N,
# puts $MTAI64N plus 36 hours into $latest,
# puts the earlier one of $wake and $latest into $wake,
# puts the last-modified time of the file "started" into $MTAI64N,
# puts $MTAI64N plus 1 hour into $earliest,
# puts the later one of $wake and $earliest into $wake,
# reports $wake in human-readable format,
# sleeps until $wake,
# and runs ./doit.
# (The statfile command belongs to the misc/fdtools package.)

exec \
setuidgid mirroruser                \
rw-add   n d1S             now1s    \
rw-match \$now1s ,H=2,M=30 wake     \
statfile -M finished                \
rw-add \$MTAI64N d36H      latest   \
rw-min \$wake \$latest     wake     \
statfile -M started                 \
rw-add \$MTAI64N d1H       earliest \
rw-max \$wake \$earliest   wake     \
sh -c '
  echo "@$wake" | tai64nlocal | sed "s/^/next run time: /"
  exec "$@"' arg0 \
rw-sleep \$wake                     \
./doit


syntax highlighted by Code2HTML, v. 0.9.1