#!/usr/local/bin/bash
#/ Usage: ghe-backup-elm-exporter
#/ Backup ELM Exporter appliance state from /data/user/elm-exporter.
#/
#/ 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"

trap_errors

bm_start "$(basename "$0")"

# Set up remote host and root backup snapshot directory based on config
host="$GHE_HOSTNAME"
backup_dir="$GHE_SNAPSHOT_DIR/elm-exporter"

# Verify rsync is available.
if ! rsync --version 1>/dev/null 2>&1; then
  log_error "rsync not found." 1>&2
  exit 1
fi

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

# Split host:port into parts
port=$(ssh_port_part "$GHE_HOSTNAME")
host=$(ssh_host_part "$GHE_HOSTNAME")

if ! ghe-ssh "$GHE_HOSTNAME" -- "[ -d '$GHE_REMOTE_DATA_USER_DIR/elm-exporter' ]"; then
  log_warn "ELM Exporter data missing. Skipping ..."
  bm_end "$(basename "$0")"
  exit 0
fi

# Make sure root backup dir exists if this is the first run
mkdir -p "$backup_dir"

# If we have a previous increment and it is not empty, avoid transferring existing files via rsync's
# --link-dest support. This also decreases physical space usage considerably.
if [ -d "$GHE_DATA_DIR/current/elm-exporter" ] && [ "$(ls -A "$GHE_DATA_DIR/current/elm-exporter")" ]; then
  link_dest="--link-dest=../../current/elm-exporter"
fi

ghe_verbose "* Transferring ELM Exporter files from $host"
rsync_command="ghe-rsync -ar \
  --rsh=\"ghe-ssh -p $port\" \
  $link_dest \
  --delete \
  --rsync-path=\"sudo -u elm-exporter rsync\" \
  \"$host:$GHE_REMOTE_DATA_USER_DIR/elm-exporter/\" \
  \"$backup_dir\""
run_rsync "$rsync_command" "elm-exporter"

bm_end "$(basename "$0")"
