#!/usr/local/bin/bash

###################################################
#
# Strips all files matching regexp in exclude_files
# from the tarball.
#
# Looks for errors on tape rewind, backup.  Mails
# the errors to $LOGMAIL when finished.
#
# 077 umask is needed to protect user privacy.
#
###################################################

umask 077

LOGFILE="/tmp/backup.log"
LOGMAIL="you@example.com"

VOLUMES="/export/home \
/export/pr0n \
/export/warez \
/export/warez \
/home/scratch \
/mnt/remote \
/var/mail"


TAPEDEV=/dev/sa0

VERBOSE=0
if [ "x$1" = "x-v" ]; then
  VERBOSE=1
fi

# Echo function with verbosness testing
# Usage: just like echo, without switches
function vecho {
  if [ $VERBOSE -eq 1 ]; then
    echo "$@"
  fi
}

vecho "Rewinding tape..."
mt -f $TAPEDEV rewind 2> $LOGFILE.err

typeset -i ERR=0
vecho "Creating tar archive..."
tar -z -c -v -f $TAPEDEV -X /admin_scripts/exclude_files $VOLUMES > $LOGFILE 2>> $LOGFILE.err
if [ $? -ne 0 ]; then
	vecho "tar did not exit gracefully.  Please check the backup integrity."
	ERR=$?
fi

vecho "Ejecting tape..."
mt -f $TAPEDEV offline > /dev/null 2>&1

typeset -i tries=0

if [ $VERBOSE -eq 1 ]; then
  echo -n "Waiting for device..."
fi
while [ $? -ne 0 ]; do
	sleep 5
	mt -f $TAPEDEV offline > /dev/null 2>&1
	tries=$tries+1
done
vecho "Done.  Waited $tries times."

gzip -f $LOGFILE

vecho "Done."
vecho `date`

if [ $ERR -ne 0 -a -s $LOGFILE.err ]; then
  cat $LOGFILE.err | mail -s "Backup Errors - `date`" $LOGMAIL
  exit 1
fi

exit 0


