#!/usr/bin/env bash
# ==========================================================================
#         ____            _                     _____           _
#        / ___| _   _ ___| |_ ___ _ __ ___     |_   _|__   ___ | |___
#        \___ \| | | / __| __/ _ \ '_ ` _ \ _____| |/ _ \ / _ \| / __|
#         ___) | |_| \__ \ ||  __/ | | | | |_____| | (_) | (_) | \__ \
#        |____/ \__, |___/\__\___|_| |_| |_|     |_|\___/ \___/|_|___/
#               |___/
#                             --- System-Tools ---
#                  https://www.nntb.no/~dreibh/system-tools/
# ==========================================================================
#
# Try-Hard
# Copyright (C) 2024-2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# Bash options:
set -eu


export TEXTDOMAIN="try-hard"
# export TEXTDOMAINDIR="${PWD}/locale"   # Default: "/usr/share/locale"

# shellcheck disable=SC1091
. gettext.sh


# ###### Usage ##############################################################
usage () {
   echo >&2 "$(gettext "Usage:") $0 max_trials delay [-q|--quiet] [-w|--verbose] [-h|--help] -- command ..."
   exit 1
}


# ###### Main program #######################################################

# ====== Handle arguments ===================================================
GETOPT="$(PATH=/usr/local/bin:${PATH} which getopt)"
options="$(${GETOPT} -o qwh --long quiet,verbose,help -a -- "$@")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
   usage
fi

VERBOSE=0
eval set -- "${options}"
while [ $# -gt 0 ] ; do
   case "$1" in
      -q | --quiet)
         VERBOSE=0
         shift
         ;;
      -w | --verbose)
         VERBOSE=1
         shift
         ;;
      -h | --help)
         usage
         # shift
         ;;
      --)
         shift
         break
         ;;
  esac
done
if [ $# -lt 3 ] ; then
   usage
fi

MAX_TRIALS="$1"
DELAY="$2"
shift 2
if [[ ! "${MAX_TRIALS}" =~ ^[0-9]*$ ]] || [ "${MAX_TRIALS}" -lt 1 ] ; then
   eval_gettext >&2 "ERROR: Invalid maximum trials \${MAX_TRIALS}!"
   echo >&2
   exit 1
fi
if [[ ! "${DELAY}" =~ ^[0-9]+$ ]] ; then
   eval_gettext >&2 "ERROR: Invalid delay \${DELAY}!"
   echo >&2
   exit 1
fi


# ====== Run loop ===========================================================
trial=0
while true ; do
   trial=$(( trial+1 ))
   if [ "${VERBOSE}" -eq 1 ] ; then
      echo -e "\x1b[34m$(date +%FT%H:%M:%S): $(eval_gettext "Trial \${trial}/\${MAX_TRIALS}: \x1b[37m$*")\x1b[0m"
   fi

   # shellcheck disable=SC2068
   $@ && exit

   if [ ${trial} -ge "${MAX_TRIALS}" ] ; then
      if [ "${VERBOSE}" -eq 1 ] ; then
         echo -e "\x1b[34m$(date +%FT%H:%M:%S): $(eval_gettext "Tried \${MAX_TRIALS} times -> giving up now!")\x1b[0m"
      fi
      exit 1
   fi
   if [ "${VERBOSE}" -eq 1 ] ; then
      echo -e "\x1b[34m$(date +%FT%H:%M:%S): $(eval_gettext "Waiting for \${DELAY} s before trying again ...")\x1b[0m"
   fi
   sleep "${DELAY}"
done
