#!/bin/bash
## ----------------------------------------------------------------------
## ----------------------------------------------------------------------
##
## File:      zip_send_rm
## Author:    mgrosso 
## Created:   Fri Oct  3 18:18:38 EDT 2003 on dhcp-172-18-102-101.looksmart.com
## Project:   apache, cronolog
## Purpose:   make damn sure the log file arrives at its destinations
## 
## Copyright (c) 2003 LookSmart. All Rights Reserved.
## 
## $Id$
## ----------------------------------------------------------------------
## ----------------------------------------------------------------------


function do_or_die()
{
    $@
    if [ $? -ne 0 ] ; then 
        logger -s -p local0.crit "$0 puking on [ $@ ]"
        exit 1
    fi
}

if [ $# == 2 ] ; then
    SCPDESTLIST=$1
    shift
fi
FILE=$1



do_or_die gzip $FILE

if [ -z $SCPDESTLIST ] ; then
    exit 0
fi

FILE=${FILE}.gz

# spawn subshells, so that each scp can suceed or fail on its own.
# while this is less efficient from a bandwidth and cpu perspective, it 
# is safer because it ensures that a hanging dest cant prevent the other 
# dests from working.

SCPDESTINATIONS=$( echo $SCPDESTLIST | sed -e 's/,/ /g' )
for DEST in $SCPDESTINATIONS ; do
    (
        HDEST=$( echo $DEST | cut -d ':' -f 1 )
        BACKUP_LINK=${HDEST}-$FILE
        do_or_die ln $FILE $BACKUP_LINK
        do_or_die scp $FILE $DEST
        do_or_die rm $BACKUP_LINK
    ) &
done
wait
# we dont delete the file unless it arrive at all destinations
# because if one destination failed, then ${DEST}-$FILE will still exist
# even after we rm $FILE
do_or_die rm $FILE
exit 0

