#!/bin/bash
#
# restores the given directory (or file) from the configured backup space

. /usr/sbin/eb-check-eb

if [ ! -d ${EBMOUNTDIR}/${EBDESTBASE} ] ; then
  echo "FATAL: Target base directory not found: ${EBMOUNTDIR}/${EBDESTBASE}"
  echo "You might have to call sudo eb-mount"
  exit 31
fi

DIR=$1
if [ -z "$DIR" ] ; then
  echo "No directory (or file) to restore given."
  exit 32
fi

if [ ! -e "$DIR" ] ; then
  echo "No such file or directory: $DIR"
  echo "To restore a deleted file or directory, either abort with Ctrl-C"
  echo " and touch or mkdir it ..."
  echo "# mkdir $DIR"
  echo "# touch $DIR"
  echo "... or press ENTER to continue anyway."
  read ENTER
  #exit 33
fi

if [ -e "$DIR" ] ; then
  if [ ! -d "$DIR" ] ; then
    if [ ! -f "$DIR" ] ; then
      echo "$DIR is neither a file nor a directory:"
      ls -ld $DIR
      exit 4
    fi
  fi
fi

export FILE="$DIR"
if [ ! -d "$DIR" ] ; then
  DIR=$(dirname $FILE)
fi

ABSDIR=$(echo "$DIR" |egrep '^/')
if [ -z "$ABSDIR" ]
then
  echo "Path not absolute: ${DIR}"
  exit 11
fi

EVILDIR=$(echo "$DIR" |egrep '^/($|dev|proc|sys)')
if [ ! -z "$EVILDIR" ]
then
  echo "Path not allowed: ${DIR}"
  exit 12
fi

if [ -d "${FILE}" ] ; then
  FILE="${FILE}/"
fi

shift
MANUALSYNCOPTIONS=$*
if [ ! -z "$MANUALSYNCOPTIONS" ] ; then
  echo "Interpreting additional parameters as rsync options: $*"
else
  echo "No additional parameters as rsync options, -n suggested."
fi

#echo "DIR=${DIR}"
#echo "FILE=${FILE}"

# OK, go to work

export BAKDESTBASE="${EBMOUNTDIR}/${EBDESTBASE}"
echo "Checking source $DIR, ${BAKDESTBASE}/${FILE}"
test -e ${BAKDESTBASE}/${FILE} || exit 52

export RSYNCOPTIONS="-r --delete --delete-after --force -g -l -o -p -v -S -t -x --timeout=60" # -W ?

echo "Restoring ${FILE}"
XSOK="no"
echo "Calling   rsync ${RSYNCOPTIONS} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} ${BAKDESTBASE}/${FILE} ${FILE}"
rsync ${RSYNCOPTIONS} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} ${BAKDESTBASE}/${FILE} ${FILE} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} && XSOK="yes"
if [ "$XSOK" = "no" ] ; then
  echo "Failed, please retry the restore command manually:"
  echo "rsync ${RSYNCOPTIONS} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} ${BAKDESTBASE}/${FILE} ${FILE} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS}"
  exit 41
fi

echo "Finished restoring ${FILE} from ${BAKDESTBASE}"


