#!/usr/bin/env 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)"

# 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
  echo "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 ..."

ghe-rsync -avz \
  -e "ghe-ssh -p $port" \
  --rsync-path='sudo -u actions rsync' \
  --exclude "mutexes" --exclude "dumps" \
  $link_dest \
  "$host:$GHE_REMOTE_DATA_USER_DIR/actions/" \
  "$GHE_SNAPSHOT_DIR/actions" 1>&3

bm_end "$(basename $0)"
