#!/usr/local/bin/bash
#/ Usage: ghe-backup-actions
#/ Take an online, incremental snapshot of all Actions data (excluding
#/ what is stored in MSSQL)
#/
#/ 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)"

trap_errors

# Set up remote host and root backup snapshot directory based on config
port=$(ssh_port_part "$GHE_HOSTNAME")
host=$(ssh_host_part "$GHE_HOSTNAME")
backup_dir="$GHE_SNAPSHOT_DIR/actions"

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

# 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 "$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/actions" ] && [ "$(ls -A $GHE_DATA_DIR/current/actions)" ]; then
  link_dest="--link-dest=$GHE_DATA_DIR/current/actions"
fi

# Transfer all Actions data from the user data directory using rsync.
ghe_verbose "* Transferring Actions files from $host ..."
rsync_command="ghe-rsync -a \
  -e \"ghe-ssh -p $port\" \
  --rsync-path='sudo -u actions rsync' \
  --exclude \"mutexes\" --exclude \"dumps\" --exclude \"tmp\" \
  $link_dest \
  \"$host:$GHE_REMOTE_DATA_USER_DIR/actions/\" \
  \"$GHE_SNAPSHOT_DIR/actions\""
run_rsync "$rsync_command" "actions"

bm_end "$(basename $0)"
