#!/bin/bash
# shellcheck disable=SC2155
if ! type "include" > /dev/null 2>&1; then
  include() {
    . "$(cd "$(dirname "$1")" && pwd)/${2}";
  };
fi
include "${BASH_SOURCE[0]}" ../pragma_once.bash
if ! pragma_once ${BASH_SOURCE[0]}; then return 0; fi
include "${BASH_SOURCE[0]}" ./global_rely/export.bash
# shellcheck source=./global_rely/export.bash


download_msys2_pkg() {
  local repo="$1"
  local pkg_name="$2"
  local pkg_root="$3"
  local sha256="${4:-}"

  check_and_create_dir_var pkg_root

  local pkg_path="${pkg_root}/${pkg_name}"
  local url="https://mirror.msys2.org/mingw/${repo}/${pkg_name}"

  if [[ -f "${pkg_path}" ]]; then
    echo "[reuse] ${pkg_path}" >&2
  else
    echo "[download] ${url}" >&2
    curl -L --fail --retry 3 \
      -o "${pkg_path}" \
      "${url}"
  fi

  if [[ -n "${sha256}" ]]; then
    echo "${sha256}  ${pkg_path}" | sha256sum -c - >&2
  fi

  printf '%s\n' "${pkg_path}"
}
