#!/bin/bash

#some internal funtions
function show_help
{
echo "Usage: grid-restore BACKUP_DIR/FILE[|DIR]_TO_RECOVER RECOVERED_FILE[DIR]_NAME [time(=now default) [--force|-f](delete existing target first)  ]"
echo "eg.: grid-restore /backup/var/log/messages ./messages 2M3D (restore file as it was 2 months and 3 days ago"
echo "eg.: grid-restore /backup/var/log/messages ./messages 2M3D --force (restore file as it was 2 months and 3 days ago, first delete the current content od .messages !)"
echo "grid-restore hostname.net::/remote/directory /etc/directory 2005-11-09T12:43:53"
exit
}

function install_info
{
echo "This script is based on rdiff-backup tool"
echo "Please install it first:"
echo "manualy: http://rdiff-backup.nongnu.org/ (python installation is also required)"
echo "or: apt-get install rdiff-backup"
echo "if above command don't works this may help:"
echo 'echo "rpm http://linuxsoft.cern.ch dag/redhat/el3/en/i386 dag" >> /etc/apt/sources.list.d/dag.list'
echo "apt-get update"
exit
}

#Checking is rdiff-backup installed in default PATH
rdiff-backup -V > /dev/null || { install_info ; exit ; } ;


if [ "$#" -eq 1 ] ; then

case ${1#-} in
   "-help"|"h")
 	how_help
	exit
       ;;
esac

fi

if [ "$#" -eq 0 ] ; then
	show_help
	exit
fi

if [ "$#" -gt 4 ] ; then
	echo "Wrong number of parameters";
	echo "I'don't know what you mean:";
	show_help;
fi

# Let's do the restore

HOW_LONG=$3
#default HOW_LONG=now
FROM_WHERE=$1
TO_WHERE=$2
FORCE_DELETE_OLDER_TARGET=0

if ! [ $HOW_LONG ]; then
HOW_LONG=now
fi

case ${4#-} in
   "-force"|"f")
        FORCE_DELETE_OLDER_TARGET=1
       ;;
esac

if ! [ $HOW_LONG ] ; then
HOW_LONG="now"
fi

echo $FORCE_DELETE_OLDER_TARGET

if [ "$FORCE_DELETE_OLDER_TARGET" -eq 1 ] ;
then
echo "WITH (--force) REMOVING OLDER TARGET";
	rm -rf $TO_WHERE;
	rdiff-backup --restore-as-of $HOW_LONG $FROM_WHERE $TO_WHERE;
else
echo "WITHOUT (--force) remove older target";
	rdiff-backup --restore-as-of $HOW_LONG $FROM_WHERE $TO_WHERE;
fi

