#!/usr/bin/env bash
# Copyright IBM Corp. 2019, 2026
# SPDX-License-Identifier: MIT

# Adapted from: https://github.com/hashicorp/vault-secrets-operator/blob/main/hack/.functions

# getGH downloads files from GitHub with optional authentication
# Usage: getGH <url> [dest_file] [num_retries]
function getGH() {
  local url="$1"
  local dest="$2"
  local num_retries="${3:-${GH_GET_RETRIES}}"

  headers=(
      '--header' "Accept: application/vnd.github+json"
      '--header' "X-GitHub-Api-Version: 2022-11-28"
  )
  if [ -n "${GITHUB_TOKEN}" ]; then
      headers+=(
          '--header' "Authorization: Bearer ${GITHUB_TOKEN}"
      )
  fi
  cmd=curl
  opts=('-sfSL')
  echo "Fetching ${url}"
  if [ -z "${dest}" ]; then
    opts+=('-O')
  else
    opts+=('-o' "${dest}")
  fi
  if [ -n "${num_retries}" ]; then
    opts+=('--retry' "${num_retries}")
  fi
  ${cmd} "${opts[@]}" "${headers[@]}" "${url}"
}
