#!/usr/bin/env bash
#/ Usage: ghe-backup-minio
#/ Take an online, incremental snapshot of all minio data
#/
#/ 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}/minio"

# Verify rsync is available.
if ! command -v rsync 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}"

# 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.
# Hilariously, this HAS to stay unquoted when you call `rsync` further
# down because when the shell interpolates this out, `rsync` will throw
# an absolute fit if this variable is quoted. Surprise!
if [[ -d "${GHE_DATA_DIR}/current/minio" ]] &&
  [[ "$(ls -A "${GHE_DATA_DIR}/current/minio")" ]]; then
    link_dest="--link-dest=${GHE_DATA_DIR}/current/minio"
fi

# Transfer all minio data from the user data directory using rsync.
ghe_verbose "* Transferring minio files from ${host} ..."
log_rsync "BEGIN: minio rsync" 1>&3
ghe-rsync \
  --archive \
  --verbose \
  --rsh="ghe-ssh -p ${port}" \
  --rsync-path='sudo -u minio rsync' \
  --exclude=".minio.sys" \
  ${link_dest} \
  "${host}:${GHE_REMOTE_DATA_USER_DIR}/minio/" \
  "${GHE_SNAPSHOT_DIR}/minio" 1>&3
log_rsync "END: minio rsync" 1>&3
bm_end "$(basename "${0}")"
