#!/usr/local/bin/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
. $( 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 [ $GHE_VERSION_MAJOR -ge 2 ] && [ $GHE_VERSION_MINOR -ge 2 ]; then
  es_port=9201
else
  es_port=9200
fi

if ! indices=$(ghe-ssh "$host" "curl -s \"localhost:$es_port/_cat/indices/audit_log*?h=index"\"); then
  echo "Error: failed to retrieve audit log indices." 1>&2
  exit 1
fi

current_index=audit_log-$(ghe-ssh "$host" 'date +"%Y-%m"')

for index in $indices; do
  if [ -f $GHE_DATA_DIR/current/audit-log/$index.gz -a $index \< $current_index ]; then
    # Hard link any older indices since they are read only and won't change
    ln $GHE_DATA_DIR/current/audit-log/$index.gz $GHE_SNAPSHOT_DIR/audit-log/$index.gz
  else
    ghe-ssh "$host" "/usr/local/share/enterprise/ghe-es-dump-json \"http://localhost:$es_port/$index\"" | gzip > $GHE_SNAPSHOT_DIR/audit-log/$index.gz
  fi
done

bm_end "$(basename $0)"
