#!/bin/sh -e
#
# rerun - retries command configurable number of times until success or failure
#
# ---
# see: https://overflow.adminforge.de/questions/8350942/placeholder#8351489
# source: https://github.com/tomsquest/dotfiles/blob/master/bin/rerun

# colors
color_success=$(tput setaf 2)
color_failure=$(tput setaf 1)
color_info=$(tput setaf 4)
color_reset=$(tput sgr0)

# config
max_attempts=${ATTEMPTS-5}
pause=${PAUSE-0}
attempt=0
exitCode=0

usage() {
  cat <<-EOF
$(basename "$0")
  a simple script that retries command a configurable number of times until success or failure

$(basename "$0") <success|failure> a <command> with arguments

examples:
  $(basename "$0") success curl 'https://example.com'
  $(basename "$0") failure curl 'https://example.com'
  ATTEMPTS=2 PAUSE=5 $(basename "$0") success curl 'https://example.com'

values:
  ATTEMPTS (default: 5) is the number of retry. ATTEMPT=0 means unlimited retries.
  PAUSE (default: 0) is the time in seconds between retries.
EOF
}

success_msg() {
  msg="$1"
  echo "${color_success}${msg}${color_reset}"
}

error_msg() {
  msg="$1"
  echo "${color_failure}${msg}${color_reset}"
}

info_msg() {
  msg="$1"
  echo "${color_info}${msg}${color_reset}"
}

if [ -z "$1" ]; then
  usage
  exit 85
fi

# type of result awaited, success or failure
type=$1
shift

if [ "${type}" != "success" ] && [ "${type}" != "failure" ]; then
  error_msg "Invalid type '${type}': must be 'success' or 'failure'"
  usage
  exit 85
fi

if [ -z "$1" ]; then
  error_msg "Missing command to run"
  usage
  exit 85
fi

rerun() {
  while [ "${max_attempts}" -eq 0 ] || [ "${attempt}" -lt "${max_attempts}" ]; do
    set +e
    "$@"
    exitCode="$?"
    set -e

    if [ "${type}" = "success" ] && [ "${exitCode}" -ne 0 ]; then
      break
    elif [ "${type}" = "failure" ] && [ "${exitCode}" -eq 0 ]; then
      break
    fi

    info_msg "Attempt ${attempt}. Retrying in ${pause} second(s)..."
    sleep "${pause}"
    attempt=$((attempt + 1))
    pause=$((pause))
  done

  if [ "${type}" = "success" ]; then
    if [ "${exitCode}" -eq 0 ]; then
      error_msg "Command succeeded ${attempt} times and never failed!"
    else
      success_msg "Command succeeded ${attempt} times before failing."
    fi
  else
    if [ "${exitCode}" -ne 0 ]; then
      error_msg "Command failed ${attempt} times and never succeeded!"
    else
      success_msg "Command failed ${attempt} times before succeeding."
    fi
  fi
}

rerun "$@"
