#!/usr/bin/env bash
#/ Usage: ghe-restore-es-hookshot
#/ Restores a backup of hookshot logs to Elasticsearch.
#/
#/ Note: This command typically isn't called directly. It's invoked by
#/ ghe-restore.
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
[ $# -lt 1 ] && print_usage

bm_start "$(basename $0)"

GHE_HOSTNAME="$1"

# Perform a host-check and establish GHE_REMOTE_XXX variables.
ghe_remote_version_required "$GHE_HOSTNAME"

last_index=$(ghe-ssh "$GHE_HOSTNAME" 'curl -s "localhost:9201/_cat/indices/hookshot-logs-*"' | cut -d ' ' -f 3 | sort | tail -2 | head -1)

indices=$(find $GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/hookshot/*.gz -print0 2>/dev/null | xargs -0 -I{} -n1 basename {} .gz)
tmp_list="$(mktemp -t backup-utils-restore-XXXXXX)"
if is_instance_configured; then
  configured=true
fi

for index in $indices; do
  if [ -z "$last_index" ] || ! [ $index \< $last_index ]; then
    echo "$index.gz" >> $tmp_list
  fi
done

if [ -s "$tmp_list" ]; 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" \
    --files-from=$tmp_list \
    "$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/hookshot/" \
    "$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/hookshot/" 1>&3

  if $CLUSTER || [ -n "$configured" ]; then
    for index in $(cat $tmp_list | sed 's/\.gz$//g'); do
      ghe_verbose "* Restoring $index"
      echo "export PATH=\$PATH:/usr/local/share/enterprise && sudo gzip -dc $GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/hookshot/$index | ghe-es-load-json 'http://localhost:9201/$index'" |
      ghe-ssh "$GHE_HOSTNAME" -- /bin/bash 1>&3
    done
  else
    ghe-ssh "$GHE_HOSTNAME" -- "sudo sh -c 'mv $GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/hookshot/* $GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/'" 1>&3
  fi

  ghe-ssh "$GHE_HOSTNAME" -- "sudo sh -c 'rm -rf $GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/hookshot/'" 1>&3

  rm $tmp_list
fi

bm_end "$(basename $0)"
