#!/bin/sh
#/ 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
cd $(dirname "$0")/../..
. share/github-backup-utils/ghe-backup-config

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

# 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

# restoring v11.10.x ES snapshot into a v2.0 appliance
elif [ "$GHE_VERSION_MAJOR" -gt 1 -a -f "$snapshot_dir/elasticsearch/elasticsearch.yml" ]; then
    ghe-ssh "$GHE_HOSTNAME" -- "sudo mkdir -p '$GHE_REMOTE_DATA_USER_DIR/elasticsearch-legacy'" 1>&3
    ghe-ssh "$GHE_HOSTNAME" -- "sudo chown elasticsearch:elasticsearch '$GHE_REMOTE_DATA_USER_DIR/elasticsearch-legacy'" 1>&3

    ghe-rsync -avz --delete \
        -e "ghe-ssh -p $(ssh_port_part "$GHE_HOSTNAME")" \
        --rsync-path="sudo -u elasticsearch rsync" \
        "$snapshot_dir/elasticsearch/" \
        "$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/elasticsearch-legacy" 1>&3

# restoring v2.0 ES snapshot into a v2.0 appliance
elif [ "$GHE_VERSION_MAJOR" -gt 1 ]; then
    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" \
        "$snapshot_dir/elasticsearch/" \
        "$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore" 1>&3

# restoring v11.10.x ES snapshot into a v11.10.x appliance
else
    # Use GNU tar on BSDs.
    TAR=tar
    if ! tar --version | grep GNU >/dev/null; then
            TAR=gtar
    fi
    cd "$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT"
    $TAR -cf - --owner=root --group=root elasticsearch |
    ghe-ssh "$GHE_HOSTNAME" -- 'ghe-import-es-indices' 1>&3
fi
