#!/bin/sh

##############################################################################
# rsnaptar
# by Nathan Rosenquist <nathan@rsnapshot.org>
#
# A quick hack of a shell script to tar up backup points from the rsnapshot
# snapshot root. Sends an e-mail to an address specified on the command line
# when finished.
#
# I set this up in cron to run once a week, take the tar files,
# and make DVD-RW backups of the latest snapshot. Your mileage may vary.
#
# http://www.rsnapshot.org/
##############################################################################

# $Id: rsnaptar,v 1.11 2007/03/22 02:50:21 drhyde Exp $

umask 0077

# DIRECTORIES
TAR_DIR="/var/dvd_backup"
SNAPSHOT_DIR="/backup/private/snapshots/daily.0"

# SHELL COMMANDS
LS="/bin/ls"
TAR="/bin/tar"
CAT="/bin/cat"
CHMOD="/bin/chmod"
CHOWN="/bin/chown"
MKDIR="/bin/mkdir"
SENDMAIL="/usr/lib/sendmail -t -oi"
HOSTNAME=`/bin/hostname`
DATE=`/bin/date +%Y-%m-%d`

# uncomment this to gpg encrypt files
# the e-mail address the notification is being sent to must have their GPG key
# in the public keyring of the user running this backup
#
GPG="/usr/bin/gpg"

# GET E-MAIL ADDRESS
if [ ! $1 ]; then
	echo "Usage: rsnaptar user@domain.com"
	exit 1
else
	TO_EMAIL=$1
fi

# MAKE ONE TAR FILE FOR EACH BACKUP POINT
${MKDIR} -p ${TAR_DIR}/${DATE}/
cd ${SNAPSHOT_DIR}
for BACKUP_POINT in `${LS} ${SNAPSHOT_DIR}`; do
	
	# GPG encrypt backups if $GPG is defined
	if test ${GPG}; then
		${TAR} --numeric-owner -cf - ${BACKUP_POINT}/ | \
			$GPG --encrypt -r $TO_EMAIL > ${TAR_DIR}/${DATE}/${BACKUP_POINT}.tar.gpg
		
	# just create regular tar files
	else
		${TAR} -czf ${TAR_DIR}/${DATE}/${BACKUP_POINT}.tar.gz ${BACKUP_POINT}/
	fi
	
done
cd -

# there are probably sensitive files here, so use the strictest permissions
${CHMOD} -R 0600 ${TAR_DIR}/${DATE}/*
${CHMOD} 0700 ${TAR_DIR}/${DATE}/

${CAT} <<EOF | ${SENDMAIL}
To: ${TO_EMAIL}
Subject: backup job complete - ${HOSTNAME}

Now is the time to backup the latest files from rsnapshot on ${HOSTNAME}
EOF
