#!/usr/local/bin/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
. $( 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 -1)

indices=$(ls -1 $GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/hookshot/*.gz 2>/dev/null | xargs -I{} -n1 basename {} .gz)

for index in $indices; do
  if [ -z "$last_index" ] || ! [ $index \< $last_index ]; then
    ghe_verbose "* Restoring $index"
    gzip -dc $GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/hookshot/$index.gz | ghe-ssh "$GHE_HOSTNAME" "/usr/local/share/enterprise/ghe-es-load-json 'http://localhost:9201/$index'" 1>&3
  fi
done

bm_end "$(basename $0)"
