#!/usr/bin/env bash
#
# retry - retries a command on key press
#
# ---
# source: https://github.com/tomsquest/dotfiles/blob/master/bin/retry

set -eu
now=$(date "+%T")

usage() {
  cat <<EOF
Usage:   $(basename "$0") <command> [arguments]
Example: $(basename "$0") curl http://localhost:8080/test
EOF
  exit 1
}

if [ "$#" -lt 1 ]; then
  printf '%s\n' "No arguments supplied, nothing to retry!" >&2
  usage
fi

while true; do
  set +e
  "$@"
  exitcode="$?"
  set -e

  if [ "${exitcode}" -eq 0 ]; then
    printf '%b\n' "\033[0;34m${now} Press any key to retry command: $*\033[0m"
  else
    printf '%b\n' "\033[0;31m${now} Failed: ${exitcode} - Press any key to retry command: $*\033[0m"
  fi

  # ask for input:
  # -n 1 : capture a single char
  # -r : recommended by ShellCheck to handle backslash
  # -s : silent, don't echo the captured char
  # -p : prompt
  read -n 1 -r -s
  # read -r exitcode
done
