#!/bin/sh
# backup.sh - version 0.1.1
# rsync-based backup script
#
# changes:
# 0.1.1 [2010-01-19] - fixed backup timestamps
#
# Short description:
# This script makes root filesystem local/remote (NFS, CIFS) backups using rsync.
# It should be running periodically by crontab.
#
# Example line to run script weekly on the first day of the week @ 4:30am:
# 30 4 * * 0 /usr/local/sbin/backup.sh 1> /dev/null
#
# Example config usage:
# BACKUP_EXP=2
# LEAD_ZEROS=3
# Above config will run first backup with current date, eg. 2009-05-12.
# It'll create a directory named 2009-05-12_001 (first revision, 3 leading zeros).
# The next backup after one week will be called 2009-05-19_002.
# We want to store two backups, so the next backup will contain files from 2009-05-12_001 -
# - backup directory will be moved to new date 2009-05-26_003, and then synchronize by rsync.
#
# copyleft (c) 2009-05-12 Damian Pasternok
# All rights reversed. <my_forename at pasternok.org>
#
### config
BACKUP_DIR=/backup	# directory where backups will be stored
BACKUP_EXP=2		# number of stored backups
LEAD_ZEROS=4		# leading zeros for backup revisions (just for clearness)
LOSTFOUND=yes		# set this to "yes" if $BACKUP_DIR is a mounted partition
ADDT_OPTS=yes		# additional pre/post backup commands (eg. remount partition)
EXCLUDE_DIRS="--exclude=$BACKUP_DIR --exclude=/dev --exclude=/proc --exclude=/sys"	# don't backup these directories
#
### code
GREEN="\033[1;32;40m"
RED="\033[1;31;40m"
WHITE="\033[1;37;40m"
CLR="\033[0m"

if [ $LOSTFOUND = yes ]; then
	LSOPT="-t -I lost+found"
else
	LSOPT="-t"
fi

if [ $ADDT_OPTS = yes ]; then
##### PRE-BACKUP COMMANDS #####
	mount $BACKUP_DIR -o rw,remount
	chmod 700 $BACKUP_DIR
fi

BACKUP_NUM=`ls $LSOPT $BACKUP_DIR | wc -l`

function check_dir {
	LAST_REV=`ls $LSOPT $BACKUP_DIR | head -1 | cut -f 2 -d _ | sed 's/\///;s/0*//'`
	((LAST_REV++))
	REV=$LAST_REV
	PRINTF="printf %0${LEAD_ZEROS}d\n $REV"
	REVS=`$PRINTF`
	NEW_BACKUP=`date +%Y-%m-%d_$REVS`
}

if [ $BACKUP_EXP = $BACKUP_NUM ]; then
	OLDEST_BACKUP=`ls $LSOPT $BACKUP_DIR | tail -1`
	echo ">>> Date of the oldest backup: $OLDEST_BACKUP"
	check_dir
	echo ">>> Moving to new date: $NEW_BACKUP ..."
	mv $BACKUP_DIR/$OLDEST_BACKUP $BACKUP_DIR/$NEW_BACKUP
	echo -e ">>>$GREEN Done.$CLR"
else
	check_dir
	echo ">>> Creating new backup directory: $NEW_BACKUP ..."
	mkdir $BACKUP_DIR/$NEW_BACKUP
	echo -e ">>>$GREEN Done.$CLR"
fi

echo -ne ">>> Making backup in: "
COUNT=5
while [ $COUNT -gt 0 ]; do
	echo -ne "$RED$COUNT$CLR "
	((COUNT--))
	sleep 1
done

echo
rsync -auH --progress --stats $EXCLUDE_DIRS / $BACKUP_DIR/$NEW_BACKUP
touch $BACKUP_DIR/$NEW_BACKUP

if [ $ADDT_OPTS = yes ]; then
##### POST-BACKUP COMMANDS #####
	mount $BACKUP_DIR -o ro,remount
fi

echo -e ">>>$GREEN Backup successfully created!$CLR"