#!/bin/sh
#
# backup-dir <dirname> <backupdir>
#
# Backup directory <dirname> (and all its subdirectories) to directory <backupdir> using rsync.
# The backup directory <backupdir>/<dirname> will be a mirror image of <dirname>.
# Preserve owner and group of each file.
# Backup symlinks as symlinks.
#
# Ron Olsen <ronolsen@comcast.net>
# 23 Mar 2014
#

# Set rsync arguments

rsync_args="--verbose --archive --delete --force"

# Check arguments for errors

if [ $# -ne 2 ]
then
    echo "Usage: backup-dir <dirname> <backupdir>"
    exit 1
fi
if [ ! -d $1 ]
then
    echo "Error: $1 is not a directory"
    exit 2
fi
if [ ! -d $2 ]
then
    echo "Error: $2 is not a directory"
    exit 2
fi

DirName="$1"
BackupDir="$2"

# Use rsync to copy files. Make <backupdir>/<dirname> a mirror image of <dirname>


if [ ! -d "$BackupDir$DirName" ]
then
    echo "Creating backup directory $BackupDir$DirName"
    mkdir -p "$BackupDir$DirName"
    if [ $? -ne 0 ]
    then
        echo "mkdir failed with error $?"
        exit $?
    fi
fi

echo "Backing up $DirName/ to $BackupDir$DirName/ using rsync $rsync_args"

rsync $rsync_args "$DirName/" "$BackupDir$DirName/"

Status=$?
if [ $Status -eq 0 ]
then
    echo "Backup complete."
else
    echo "rsync failed with error $Status. Backup failed."
fi
exit $Status
