#!/bin/bash
#
# mrsgui/scripts/mrsgui-svn-retry/mrsgui-svn-retry ---
#
# Retry the svn commands.
# https://bitbucket.org/hbaspecto/mrsgui/src/master/scripts/msrgui-svn-retry
#
# This is a bit of a hack to retry "svn update"s,
# which seems to fail too often.
#
# After a meeting with the clients,
# we found that their internet connection was very slow.
# So we are going to follow up with their IT team.

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} ${1+$@}"

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

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

#####

loop_cnt=1
while [[ 1 = 1 ]]
do
  # cleanup in case the last run left trash.
  svn cleanup

  # debugging.
  # echo "### cnt=${loop_cnt} ### ${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
