#!/usr/bin/env bash
#/ Usage: ghe-rsync
#/ Run rsync with silenced vanished file warnings (non-critical).
#
# Based on the rsync-no-vanished support script included with rsync:
# https://bugzilla.samba.org/show_bug.cgi?id=10356

set -o pipefail

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

# Don't use the feature checker for expected parameters as it can cause issues with server paths
# Check for --ignore-missing-args parameter support and remove if unavailable.
if rsync -h | grep '\-\-ignore-missing-args' >/dev/null 2>&1; then
  parameters=("$@")
else
  for parameter in "$@"; do
    [[ ! $parameter == "--ignore-missing-args" ]] && parameters+=("$parameter") || ignore23=1
  done
fi

# This prepends `--trust-sender` to the parameters if supported by the current version of rsync 
# to mitigate the degradation of performance due to the resolution of CVE-2022-29154
# shellcheck source=share/github-backup-utils/ghe-rsync-feature-checker
# shellcheck disable=SC2046
if [ "$($( dirname "${BASH_SOURCE[0]}" )/ghe-rsync-feature-checker --trust-sender)" == "true" ]; then
  parameters=("--trust-sender" "${parameters[@]}")
fi

# This adds `--compress` to the parameters if supported by the current version of rsync
# shellcheck source=share/github-backup-utils/ghe-rsync-feature-checker
# shellcheck disable=SC2046
if [ "$($( dirname "${BASH_SOURCE[0]}" )/ghe-rsync-feature-checker --compress)" == "true" ] && [ "$GHE_RSYNC_COMPRESSION_ENABLED" = "yes" ]; then
  parameters+=("--compress")
fi

# This loads the $GHE_EXTRA_RSYNC_OPTS from the config file if available then adds them
# to the parameters and skip adding if already present in the parameters
# shellcheck source=share/github-backup-utils/ghe-rsync-feature-checker
# shellcheck disable=SC2046
if [ -n "$GHE_EXTRA_RSYNC_OPTS" ]; then
  for extra_opt in $GHE_EXTRA_RSYNC_OPTS; do
    if [ "$($( dirname "${BASH_SOURCE[0]}" )/ghe-rsync-feature-checker "$extra_opt")" == "true" ]; then
      parameters+=("$extra_opt")
    fi
  done
fi

ignore_out='^(file has vanished: |rsync warning: some files vanished before they could be transferred)'
rsync_version_check=$(rsync --version | grep -E "version 3.[0-9]*.[0-9]*")
if [ -n "$rsync_version_check" ]; then
  # rsync >= 3.x sends errors to stderr. so, we need to redirect to stdout before the pipe
  rsync "${parameters[@]}" 2>&1 | (grep -E -v "$ignore_out" || true)
else
  # rsync <3.x sends errors to stdout.
  rsync "${parameters[@]}" | (grep -E -v "$ignore_out" || true)
fi
res=$?

# Suppress exits with 24.
if [ $res = 24 ]; then
  res=0
fi

# Suppress exits with 23 if --ignore-missing-args was unavailable.
if [ $res = 23 ] && [ -n "$ignore23" ]; then
  res=0
fi

exit $res
