#!/bin/sh
set -eu

# Fetch helper contract:
#   DEP_PKG_MIRROR=https://mirror.example.com/monok8s
#   mirror URL = ${DEP_PKG_MIRROR}/${mirror_path}

if [ "$#" -ne 3 ]; then
    echo "usage: fetch-artifact <mirror-path> <output-file> <upstream-url>" >&2
    exit 2
fi

mirror_path="$1"
out="$2"
upstream_url="$3"

mkdir -p "$(dirname "$out")"
rm -f "$out"

if [ -n "${DEP_PKG_MIRROR:-}" ]; then
    mirror_url="${DEP_PKG_MIRROR%/}/${mirror_path}"
    echo "fetch-artifact: trying mirror: ${mirror_url}" >&2
    if curl -fL --retry 3 -o "$out" "$mirror_url"; then
        exit 0
    fi
    rm -f "$out"

    if [ "${DEP_PKG_OFFLINE:-0}" = "1" ]; then
        echo "fetch-artifact: mirror miss and DEP_PKG_OFFLINE=1: ${mirror_url}" >&2
        exit 1
    fi
fi

if [ "${DEP_PKG_OFFLINE:-0}" = "1" ]; then
    echo "fetch-artifact: DEP_PKG_OFFLINE=1 and no usable mirror for ${mirror_path}" >&2
    exit 1
fi

echo "fetch-artifact: fetching upstream: ${upstream_url}" >&2
curl -fL --retry 3 -o "$out" "$upstream_url"
