#!/usr/bin/env bash
#/ Usage: ghe-backup-es-audit-log
#/ Take a backup of audit logs in Elasticsearch.
#/
#/ Note: This command typically isn't called directly. It's invoked by
#/ ghe-backup.
set -e

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

bm_start "$(basename $0)"

# Set up remote host and root elastic backup directory based on config
host="$GHE_HOSTNAME"

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

# Make sure root backup dir exists if this is the first run
mkdir -p "$GHE_SNAPSHOT_DIR/audit-log"

if ! indices=$(ghe-ssh "$host" "curl -s \"localhost:9201/_cat/indices/audit_log*?h=index,pri.store.size&bytes=b\""); then
  log_error "ghe-backup-es-audit-log: Failed to retrieve audit log indices." 1>&2
  exit 1
fi

# Exit if no indices were found
[ -z "$indices" ] && exit

# Determine if the audit log migration has occurred or is needed.
if echo 'set -o pipefail; ! test -e /data/user/common/es-scan-complete && test -f /usr/local/share/enterprise/run-audit-log-transitions.sh' | ghe-ssh "$host" /bin/bash; then
  if echo 'set -o pipefail; echo n | /usr/local/share/enterprise/run-audit-log-transitions.sh > /dev/null 2>&1 && touch /data/user/common/es-scan-complete' | ghe-ssh "$host" /bin/bash; then
    touch $GHE_SNAPSHOT_DIR/es-scan-complete
  fi
fi

IFS=$'\n'
for index in $indices; do
  IFS=' '
  set $index
  index_name=$1
  index_size=$2

  if [[ -f $GHE_DATA_DIR/current/audit-log/$index_name.gz && $(cat $GHE_DATA_DIR/current/audit-log/$index_name.gz.size 2>/dev/null || true) -eq $index_size ]]; then
    ghe_verbose "* Linking unchanged audit log index: $index_name"
    # Hard link any indices that have not changed since the last backup
    ln $GHE_DATA_DIR/current/audit-log/$index_name.gz $GHE_SNAPSHOT_DIR/audit-log/$index_name.gz
    ln $GHE_DATA_DIR/current/audit-log/$index_name.gz.size $GHE_SNAPSHOT_DIR/audit-log/$index_name.gz.size
  else
    ghe_verbose "* Performing audit log export for index: $index_name"
    echo "/usr/local/share/enterprise/ghe-es-dump-json \"http://localhost:9201/$index_name\" | pigz" | ghe-ssh "$host" -- /bin/bash > $GHE_SNAPSHOT_DIR/audit-log/$index_name.gz
    echo $index_size > $GHE_SNAPSHOT_DIR/audit-log/$index_name.gz.size
  fi
done

bm_end "$(basename $0)"
