#!/bin/bash

## Copyright (C) 2025 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

## 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

# shellcheck disable=SC1091
source /usr/libexec/helper-scripts/log_run_die.sh

# Function to execute the command and capture the exit status
execute_command() {
  local exit_code
  "$@"
  exit_code=$?
  if (( exit_code == 0 )); then
    log info "Command exited with status: $exit_code"
  else
    log warn "Command exited with status: $exit_code"
  fi
  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
    log info "Attempt $retry_counter of $max_retries..."
    execute_command "$@"
    exit_code="$?"
    if (( exit_code == 0 )); then
      log info "Command succeeded on attempt $retry_counter."
      return 0
    fi
    log warn "Command failed on attempt $retry_counter. Retrying in $retry_delay seconds..."
    sleep "$retry_delay"
  done

  log error "Command failed after $max_retries attempts."
  return "$exit_code"
}

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