#!/usr/bin/env bash
set -euo pipefail

output_file=""
curl_args=()
args=("$@")
skip_next=false
for ((i = 0; i < ${#args[@]}; i++)); do
  if [[ "${skip_next}" == "true" ]]; then
    skip_next=false
    continue
  fi
  case "${args[$i]}" in
    -o|--output)
      if ((i + 1 < ${#args[@]})); then
        output_file="${args[$((i + 1))]}"
        skip_next=true
      fi
      ;;
    -o*)
      output_file="${args[$i]#-o}"
      ;;
    --output=*)
      output_file="${args[$i]#--output=}"
      ;;
    *)
      curl_args+=("${args[$i]}")
      ;;
  esac
done

for attempt in 1 2 3; do
  command=(
    curl
    --http1.1
    --fail
    --show-error
    --location
    --retry 5
    --retry-delay 5
    --retry-max-time 300
    --retry-connrefused
    --retry-all-errors
  )
  if [[ -n "${output_file}" ]]; then
    command+=(--output "${output_file}")
  fi
  command+=("${curl_args[@]}")
  if "${command[@]}"; then
    if [[ -z "${output_file}" || -s "${output_file}" ]]; then
      exit 0
    fi
    echo "omni-curl: curl succeeded but output file is missing or empty: ${output_file}" >&2
  fi
  if [[ -n "${output_file}" ]]; then
    rm -f "${output_file}"
  fi
  sleep $((attempt * 5))
done

echo "omni-curl: failed after retries: $*" >&2
exit 1
