#!/bin/sh
# bin/$RCSfile$  $Revision$

# script to backup enstore log files to the backup node

set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# information specific to Fermilab
#gang=`gang`
#thisNode=${gang}srv2
#rdistNode=${gang}srv3.fnal.gov


#Check if ENSTORE_DIR is set.
if [ -z `echo $ENSTORE_DIR` ]; then
   echo "ENSTORE_DIR not set."
   exit 1
fi
#Get the log directory.
log_dir=`enstore conf --show crons log_dir --timeout 10 --retries 3`
if [ $? -ne 0 ]; then
   echo "Unable to obtain log directory."
   exit 1
fi
#Get the backup node.
backup_node=`enstore conf --show crons backup_node --timeout 10 --retries 3`
if [ $? -ne 0 ]; then
   echo "Unable to obtain backup node."
   exit 1
fi
#Get the backup directory.
backup_dir=`enstore conf --show crons backup_dir --timeout 10 --retries 3`
if [ $? -ne 0 ]; then
   echo "Unable to obtain backup dir."
   exit 1
fi

filePathBackup=$backup_dir/`basename $log_dir`-backup

# function to list command, execute it and list status
doit() { echo "$1"
	 eval "nice -n 10 $1"
	 status=$?
	 echo "Status= $status"
	 if [ $status -ne 0 ]; then exit $status; fi
	 echo
       }

cmd="$ENSTORE_DIR/sbin/enrsh $backup_node mkdir -p \"$backup_dir\""

doit "$cmd"


# cron is scheduled every 15 minutes, so time out after 10
cmd="/usr/bin/rsync -e $ENSTORE_DIR/sbin/enrsh -rlpgtx --delete \
      --timeout=600 --blocking-io \
      ${log_dir}/LOG-* enstore@${backup_node}:${filePathBackup}"

doit "$cmd"
