#!/usr/bin/env 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"

# 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

  ghe-rsync -avz --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" 1>&3

  # restoring in >=2.14 will remove incompatible indices created with 1.x.
  if [ "$GHE_VERSION_MAJOR" -eq 2 ] && [ "$GHE_VERSION_MINOR" -ge 14 ]; then
    ghe-ssh "$GHE_HOSTNAME" -- "sudo /usr/local/share/enterprise/ghe-es-remove-1x-indices"
  fi
fi

bm_end "$(basename $0)"
