#!/usr/bin/env bash
#/ Usage: ghe-restore-es-audit-log
#/ Restores a backup of audit 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"

indices=$(find $GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/audit-log/*.gz -print0 2>/dev/null | xargs -0 -I{} -n1 basename {} .gz)

# Platform neutral and robust method of determining last month
this_yr=$(date +"%Y")
this_mth=$(date +"%-m")
last_mth=$(( $this_mth - 1 ))
last_yr=$this_yr
if [ "$last_mth" = 0 ]; then
  last_mth=12
  last_yr=$(( $this_yr - 1 ))
fi

last_month=$(printf "audit_log(-[0-9]+)?-%4d-%02d(-[0-9]+)?" $last_yr $last_mth)
current_month=$(printf "audit_log(-[0-9]+)?-%4d-%02d(-[0-9]+)?" $this_yr $this_mth)

tmp_list="$(mktemp -t backup-utils-restore-XXXXXX)"
if is_instance_configured; then
  configured=true
fi

# Only restore indices that don't exist and the last two months' indices.
for index in $indices; do
  if ! ghe-ssh "$GHE_HOSTNAME" "curl -f -s -XGET http://localhost:9201/$index > /dev/null" || [[ $index =~ $last_month ]] || [[ $index =~ $current_month ]]; 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
  log_rsync "BEGIN: es-audit log rsync" 1>&3
  ghe-rsync -av --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/audit-log/" \
    "$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/audit-log/" 1>&3
  log_rsync "END: es-audit log rsync" 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 pigz -dc $GHE_REMOTE_DATA_USER_DIR/elasticsearch-restore/audit-log/$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/audit-log/* $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/audit-log/'" 1>&3

  rm $tmp_list
fi

bm_end "$(basename $0)"
