#!/bin/bash
#
# mrsgui/scripts/svn-retry/svn-retry ---
#
# Retry the svn commands.
# https://bitbucket.org/hbaspecto/mrsgui/src/master/scripts/svn-retry
#
# This is a bit of a hack to retry svn checkout,
# which seems to fail too often.
#

export SVN_RETRY_DIR=$(builtin cd $(dirname ${BASH_SOURCE[0]}) ; builtin pwd)

# set -o errexit

#####

# Are we debugging?
opt_debug="${SVN_RETRY_DEBUG:-0}"

# The real svn command.
opt_svn_exe="${SVN_RETRY_SVN_EXE:-/usr/bin/svn-exe}"
# The number of times to retry.
opt_retry_cnt="${SVN_RETRY_RETRY_CNT:-5}"
# Seconds to sleep between retrys.
opt_sleep="${SVN_RETRY_SLEEP:-5}"

#####

if [[ "${opt_debug}" = 1 ]]
then
  set -xv
fi

#####

# Make the command by putting the real svn program in place.
real_cmd="${opt_svn_exe} ${@}"

# only retry "checkout" subcommands
subcommand="${1:-}"

if [[ "${subcommand}" != "checkout" ]]
then
  # wont return
  exec ${real_cmd}
fi

#####

loop_cnt=1
while [[ 1 = 1 ]]
do
  # debugging.
  # echo "### ${real_cmd}"
  ${real_cmd}
  # remember the return value
  rv="$?"
  # it was ok.
  if [[ "${rv}" = 0 ]]
  then
    exit "${rv}"
  fi

  loop_cnt=$(( ${loop_cnt} + 1 ))
  if [[ "${opt_retry_cnt}" -lt "${loop_cnt}" ]]
  then
    exit "${rv}"
  fi

  # failed - wait for a bit.
  sleep "${opt_sleep}"

done
