#!/bin/bash
# rsyncs subscription RBLs

name=$(basename $0)

homedir=/usr/local/collaboration
confdir=${homedir}/rbldnsd
lockfile="${confdir}/${name}.lock"

rsync_opts="-L -t --timeout=120"
log="logger -p cron.info -t ${name}[$$]"

date=$(date +'%F %T')
host=$(hostname | cut -f1 -d.)
verify=0
notifycmd="cronmail \"${host}: $name results $date\""
notifywho=blackops.root@umich.edu

. /usr/libexec/comint/setup

notify() {
    cat $tmpfile | $log
    cat $tmpfile | eval ${notifycmd} ${notifywho}
}

mkdir -p $workdir
cd $workdir

if [[ -f $lockfile ]]; then
    echo "Lockfile $lockfile already exists, terminating run" >> $tmpfile
    notify
    cleanup
    exit 1
fi

touch $lockfile
trap 'rm -f $lockfile ; exit 1' 1 2 3 15

errors=0

for bl in $rsync_files ; do
    local_file="${bl}.tmp"
    remote_file="${rsync_base}/${bl}${rsync_files_suffix}"
    if [[ -f $bl ]]; then
	cp -p $bl $local_file
    else
	touch $local_file
    fi

    try=0
    success=0

    while [[ $try -lt 5 && $success -ne 1 ]]; do
        (( try++ ))
        if rsync $rsync_opts $remote_file $local_file &>> $tmpfile ; then
            success=1
        else
            echo "rsync for $bl failed" >> $tmpfile
            sleep 3
        fi
    done

    if [[ $success -ne 1 ]]; then
        mv -f $local_file ${local_file}.failed &>> $tmpfile
        (( errors++ ))
        continue
    fi

    if [[ ! -s $local_file ]]; then
	echo "synced copy of $bl is empty" >> $tmpfile
	mv -f $local_file ${local_file}.empty &>> $tmpfile
	(( errors++ ))
        continue
    fi

    if cmp -s $local_file $bl ; then
        echo "$bl is unchanged" >> $tmpfile
        continue
    fi

    if [[ $verify -eq 1 ]]; then
        crc=$(tail -1 $local_file | awk '{print $3}')
        if [[ $(sed '$d' $local_file | cksum | awk '{print $1}') = $crc ]]; then
            echo "Successfully verified $local_file" >> $tmpfile
        else
            echo "CRC verification of $local_file failed" >> $tmpfile
            mv -f $local_file ${local_file}.failed &>> $tmpfile
            (( errors++ ))
            continue
        fi
    fi

    mv -f $local_file $bl
done

[[ $errors -gt 0 ]] && notify

cleanup
rm -f $lockfile
