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

. /usr/lib/bsclient/load_environment

DIR=$1
if [ -z "$DIR" ] ; then
  echo "No directory (or file) to restore given."
  exit 2
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 3
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 RSYNCOPTIONS="-r --compress --partial --progress --delete --delete-after --force -g -l -o -p -v -S -t -x --timeout=8"
if [ -z "${BAKSSHIDFILE}" ] ; then
  RSYNCOPTIONS="${RSYNCOPTIONS} --rsh "'"'"ssh -i ${BAKSSHIDFILE}"'"'
else
  RSYNCOPTIONS="${RSYNCOPTIONS} --rsh ssh"
fi

echo "Restoring ${FILE}"
XSOK="no"
echo 'Calling   SSH_AUTH_SOCK="" SSH_CLIENT="" SSH_CONNECTION="" SSH_TTY=""'" rsync ${RSYNCOPTIONS} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} ${BAKUSER}@${BAKHOST}:${BAKDESTBASE}/${FILE} ${FILE}"
SSH_AUTH_SOCK="" SSH_CLIENT="" SSH_CONNECTION="" SSH_TTY="" rsync ${RSYNCOPTIONS} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} ${BAKUSER}@${BAKHOST}:${BAKDESTBASE}/${FILE} ${FILE} ${SSHIDFILEOPTION} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} && XSOK="yes"
if [ "$XSOK" = "no" ] ; then
  echo "Failed, please retry the restore command manually:"
  echo 'SSH_AUTH_SOCK="" SSH_CLIENT="" SSH_CONNECTION="" SSH_TTY=""'" rsync ${RSYNCOPTIONS} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS} ${BAKUSER}@${BAKHOST}:${BAKDESTBASE}/${FILE} ${FILE} ${SSHIDFILEOPTION} ${SYNCOPTIONS} ${MANUALSYNCOPTIONS}"
  exit 21
fi

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


