#!/usr/local/bin/bash
#/ Usage: ghe-restore-es-rsync <host>
#/ Restore an rsync snapshot of all Elasticsearch data to a GitHub instance.
#/
#/ Note: This script typically isn't called directly. It's invoked by the
#/ ghe-restore command when the rsync strategy is used.
set -e

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

trap_errors

# Show usage and bail with no arguments
[ -z "$*" ] && print_usage

bm_start "$(basename $0)"

# Grab host arg
GHE_HOSTNAME="$1"

# Perform a host-check and establish the remote version in GHE_REMOTE_VERSION.
ghe_remote_version_required "$GHE_HOSTNAME"

# The snapshot to restore should be set by the ghe-restore command but this lets
# us run this script directly.
: ${GHE_RESTORE_SNAPSHOT:=current}

# The directory holding the snapshot to restore
snapshot_dir="$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT"

# Transfer all ES data from the latest snapshot to the GitHub instance.
if [ ! -d "$snapshot_dir/elasticsearch" ]; then
  echo "Warning: Elasticsearch backup missing. Skipping ..."
  exit 0

else
  ghe-ssh "$GHE_HOSTNAME" -- "sudo mkdir -p '$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore'" 1>&3
  ghe-ssh "$GHE_HOSTNAME" -- "sudo chown elasticsearch:elasticsearch '$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore'" 1>&3
  if (( ${GHE_VERSION_MINOR} >= 13 && ${SNAPSHOT_VERSION#*.} >= 13 )); then
    rsync_command="ghe-rsync -a --delete \
      -e \"ghe-ssh -p $(ssh_port_part "$GHE_HOSTNAME")\" \
      --rsync-path=\"sudo -u elasticsearch rsync\" \
      --exclude \"_state\" \
      --copy-dest=\"$GHE_REMOTE_DATA_USER_DIR/elasticsearch\" \
      \"$snapshot_dir/elasticsearch/\" \
      \"$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore\""
  else
    rsync_command="ghe-rsync -a --delete \
      -e \"ghe-ssh -p $(ssh_port_part "$GHE_HOSTNAME")\" \
      --rsync-path=\"sudo -u elasticsearch rsync\" \
      --copy-dest=\"$GHE_REMOTE_DATA_USER_DIR/elasticsearch\" \
      \"$snapshot_dir/elasticsearch/\" \
      \"$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore\""
  fi
  run_rsync "$rsync_command" "elasticsearch"
fi

bm_end "$(basename $0)"
