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

# 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

ignoreout='^(file has vanished: |rsync warning: some files vanished before they could be transferred)'
rsync_version_check=`rsync --version | egrep "version 3.[0-9]*.[0-9]*"`
if [ ! -z "$rsync_version_check" ]; then
  # rsync >= 3.x sends errors to stderr. so, we need to redirect to stdout before the pipe
  rsync "${parameters[@]}" $GHE_EXTRA_RSYNC_OPTS 2>&1 | (egrep -v "$ignoreout" || true)
else
  # rsync <3.x sends errors to stdout.
  rsync "${parameters[@]}" $GHE_EXTRA_RSYNC_OPTS | (egrep -v "$ignoreout" || 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
