#!/bin/bash
#
#
#

REMOTE_SYSTEM_USER=backupuser
RESTORE_SERVER=$1
DATABASE_SERVER=$2
STAGE=$3
DATABASE_ENGINE=$4

# currently it defaults to todays date
DATE=$(date +%F)

LOCAL_BACKUP_DIR="${HOME}/backups/${STAGE}/${DATABASE_ENGINE}/${DATABASE_SERVER}"
BACKUP_FILE_FOR_TRANSFER=$(find "${LOCAL_BACKUP_DIR}/${DATE}/" -name *.gz.gpg | tail -n 1)

REMOTE_BACKUP_DIR="/home/${REMOTE_SYSTEM_USER}/backups/${STAGE}/${DATABASE_ENGINE}/${DATABASE_SERVER}"
DEST_DIR="${REMOTE_BACKUP_DIR}/${DATE}/"

if [ ! -f $BACKUP_FILE_FOR_TRANSFER ]; then
   echo "BACKUP_FILE_FOR_TRANSFER not found. EXIT" && exit 1
fi

# avoid "REMOTE HOST IDENTIFICATION HAS CHANGED" - errors due to dynamic created server on restore process
ssh-keygen -f "/home/backuphamster/.ssh/known_hosts" -R ${RESTORE_SERVER}

SSH_OPTIONS='-o StrictHostKeyChecking=no'

# needed due to unknown rsync option --mkpath in rsync version 3.1.3
ssh ${SSH_OPTIONS} ${REMOTE_SYSTEM_USER}@${RESTORE_SERVER} "mkdir -p ${DEST_DIR}"

rsync -v -e "ssh ${SSH_OPTIONS}" $BACKUP_FILE_FOR_TRANSFER ${REMOTE_SYSTEM_USER}@${RESTORE_SERVER}:${DEST_DIR}

BKP_FILE_TRANSFERRED=$(echo $BACKUP_FILE_FOR_TRANSFER | awk -F / '{ print $NF}')

ssh ${SSH_OPTIONS} ${REMOTE_SYSTEM_USER}@${RESTORE_SERVER} "test -f ${DEST_DIR}${BKP_FILE_TRANSFERRED}"

