#!/bin/bash

## using 'retry' with '< /dev/null' due to upstream bug:
## https://github.com/minfrin/retry/issues/20
## Also destroys colors.
#retry --times=5 --delay=3 -- "$@" < /dev/null

# Function to execute the command and capture the exit status
execute_command() {
   "$@"
   local exit_code=$?
   echo "$0: Command exited with status: $exit_code"
   return $exit_code
}

# Main function to handle retries
attempt_command() {
    local max_retries=5
    local retry_delay=5
    local retry_counter
    local exit_code

    for retry_counter in $(seq 1 "$max_retries") ; do
       echo "$0: Attempt $retry_counter of $max_retries..."
       execute_command "$@"
       exit_code=$?
       if [ $exit_code -eq 0 ] ; then
          echo "$0: Command succeeded on attempt $retry_counter."
          return 0
       fi
       echo "$0: Command failed on attempt $retry_counter. Retrying in $retry_delay seconds..."
       sleep "$retry_delay"
    done

    echo "$0: Command failed after $max_retries attempts."
    return $exit_code
}

# Call the main function with all script arguments
attempt_command "$@"
exit_code=$?
exit $exit_code
