#! /bin/bash

# /etc/cron.daily/fmirror
#
# run the scheduled fmirror jobs. 
#
# Author: Craig Sanders <cas@taz.net.au>
#
# Copyright status: This script is copyright and licensed under the
# terms of the GNU General Public License.
#
# Revision History:
# v0.1: Dec 1997
#   - first version, not released to public.  various config values were
#     hard-coded into the script.
# v0.2 1998-01-10
#   - modified to use /etc/fmirror/config for all user-changeable
#     configuration values (JOBS, NUMLOGS, and RUN_IN_BACKGROUND)
# v0.3 1998-01-10
#   - added support for daily and weekly jobs
#   - added lots of helpful comments in the config file
# v0.4 1998-03-15
#   - used tempfile to get a tempory file for security reasons.

#set -x

confdir=/etc/fmirror
logdir=/var/log/fmirror

# if logdir doesn't exist then create it.
[ -d $logdir ] || mkdir -p $logdir

# read in the config file
. $confdir/config

# allow command line override of which jobs to run
if [ -n "$1" ] ; then
    MIRRORS="$@"
else
    MIRRORS=$JOBS
fi

# strip off .conf in case the user has ignored the instructions in
# /etc/fmirror/config saying to list only the base name.
MIRRORS=$(echo $MIRRORS | sed -e 's/\.conf//g')

do_it() {
    run=/var/run/fmirror.$1
    if [ ! -e $run ] ; then 
        touch $run
        tmpfile=`tempfile --name /tmp/fmirror.log.$1.$$.$(date +%s)`
        LOG=$logdir/$1.log

        (
            [ -e $LOG ] && savelog -c $NUMLOGS $LOG 

            # run the mirror job
            rm -f ls-lR ls-lR.gz
            conf="$confdir/$1.conf"
            fmirror -f $conf >/dev/null

            # create the local ls-lR.gz file
            localdir=`grep -i "^localdir:" $conf | cut -f2`
            cd $localdir
            # use full path to ls, just in case it is aliased to 'ls -F' or
            # something.
            /bin/ls -lR >ls-lR
            gzip -9f ls-lR 
        ) >$tmpfile 2>&1

	if [ -n "$MAILTO" ] ; then
	  cat $tmpfile | mail $MAILTO
	fi

        rm -f $run
        mv $tmpfile $LOG
    fi
}

for i in $MIRRORS ; do
    if [ "$RUN_IN_BACKGROUND" = "1" ] ; then 
        do_it $i &
    else
        do_it $i
    fi
done

