#!/bin/sh -
#
# Copyright (c) 2005 Matthew Burnside
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Usage:
#
#    backup localdir type [[user@]host:]dir1 ...
#
#  Backups are rsynced to localdir/type.  For example, you
#  might create the following crontab entry:
#
#    30 * * * * /bin/sh backup.sh backups hourly alice@foo.com:/home
#
#  This will make hourly backups of alice@foo.com:/home to
#  backups/hourly.0 and then rotate it to backups/hourly.1, etc.
#
rsync=/usr/bin/rsync
ssh=/usr/bin/ssh

rotmax=3

if [ $# -le 2 ]; then
    echo "Usage: backup localdir type [[user@]host:]dir1 ..."
    exit 1
fi

ldir=$1
type=$2
shift 2

if [ -e $ldir/$type.$rotmax ]; then
    rm -rf $ldir/$type.$rotmax
fi

i=$rotmax
while [ $i -gt 0 ]; do
    let i=i-1;
    if [ -e $ldir/$type.$i ]; then
	mv $ldir/$type.$i $ldir/$type.$((i+1))
    fi
done

if [ -e $ldir/$type.1 ]; then
    cp -al $ldir/$type.1 $ldir/$type.0
else
    mkdir -p $ldir/$type.0
fi

for dir in $*; do
    echo "Backing up: " $dir
    $rsync --delete -avze $ssh $dir $ldir/$type.0
done

if [ $? -ne 0 ]; then
    echo "Backup failed: unable to rsync"
    exit 1
else
    echo "Backup completed"
fi

exit 0

