#!/bin/bash
# Copyright (C) 2008 - 2015 x-stream.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# restore-dir [--mirror] <dirname> <backupdir>
#
# Restore directory <dirname> from directory <backupdir> using rsync.
# Files from the backup directory replace missing files in <dirname>.
# Default: no existing files in <dirname> are overwritten or deleted.
#
# Ron Olsen <ronolsen@comcast.net>
# 28 Mar 2014
#
# Default is to replace missing files in <dirname> from <backupdir>/<dirname>
# using rsync "--ignore-existing" option.
# If --mirror is specified, make <dirname> a mirror of <backupdir>/<dirname>
# using rysnc "--delete --force" options.
#

Usage="restore-dir [--mirror] <dirname> <backupdir>\n
Restore files to <dirname> from <backupdir>/<dirname>\n
Default is to replace missing files in <dirname> from <backupdir>/<dirname>.\n
--mirror: make <dirname> a mirror of <backupdir>/<dirname>"

if [ $# -lt 2 ]
then
    echo -e $Usage
    exit 1
fi

# Set rsync arguments

rsync_args="--verbose --archive --ignore-existing"

case $1 in
--mirror)
    rsync_args="--verbose --archive --force --delete"
    shift ;;
-*)
    echo "Invalid option $1"
    echo -e $Usage
    exit 1
esac 

# Check arguments for errors

if [ $# -ne 2 ]
then
    echo -e $Usage
    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. Restore missing files in $DirName from $BackupDir

echo "Restoring $DirName/ from $BackupDir$DirName/ using rsync $rsync_args"

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

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