#!/bin/bash
#set -x
# Author: Dean Wilson
# Created on: 2005/12/11
# Version: 0.3
# Last Updated: 2005/12/22
# changes: add a search path to avoid whole fs scans
# changes: changed the external binary checking

# this script gathers a list of all RCS directories on the current
# machine and puts them in a tgz file for easier backups. you may want
# to tweak FINDOPT or TAROPT to suit your environment.

STARTEPOCH=$(date +'%s')

#################################
# prerequisites - these should all exist on modern Linux machines.
#################################

binaries=$(cat<<all_required_binaries
  basename
  date
  expr
  find
  hostname
  logger
  mktemp
  tar
all_required_binaries)

#################################
# sanity check to ensure all binaries are present.
#################################

# sanity checks.
for required_binary in $binaries; do
  which $required_binary > /dev/null
  if [ "$?" != '0' ];then
    printf "$0: No usable '$required_binary' in '$PATH'\n"
    exit 1
  fi
done

#################################
# Application settings.
#################################
APPNAME=$(basename $0)
TODAY=$(date +'%Y_%m_%d')
BACKUPFILE=/var/backups/$(hostname -f)_rcsbackup_$(date +'%Y_%m_%d').tgz
TAROPTS="-czf $BACKUPFILE --atime-preserve --preserve -T "
SEARCHPATH=/etc/backuprcs_searchpath.conf
FINDOPTS=" -name RCS -type d"


#################################
# get the handle to use to hold the results
#################################
TMPFILE=$(mktemp -q /tmp/$APPNAME.XXXXXX)

if [ $? -ne 0 ]; then
  printf "$0: Can't create temp file, exiting...\n"
  exit 2
fi


#################################
# get the search paths to avoid whole fs scans
#################################

if [ -e "$SEARCHPATH" ];then
  for searchpath in `cat $SEARCHPATH`
  do
    if [ -e "$searchpath" ];then
      find $searchpath $FINDOPTS >> $TMPFILE 2>/dev/null
    else
      echo "$APPNAME: '$searchpath' doesn't exist! Not backing it up..."
    fi
  done
else
  searchpath=/
  find $searchpath $FINDOPTS >> $TMPFILE 2>/dev/null
fi


#################################
# get the RCS directories and tar them up.
if [ -s "$TMPFILE" ];then
  tar $TAROPTS $TMPFILE 2>&1 | grep -v 'Removing leading' # hack
fi

#################################
# calculate how long it's been running for.
FINISHEPOCH=$(date +'%s')
TOTALTIME=$(expr $FINISHEPOCH - $STARTEPOCH)

#################################
# clean up
logger -i -p local0.notice -t $APPNAME "RCS Backup run completed. $TOTALTIME seconds"
rm $TMPFILE
