#!/usr/bin/env bash
# Authenticate the builder to Docker Hub before any e2e image build.
#
# celilo#1376: the e2e base images are digest-pinned, which makes a pull
# REPRODUCIBLE — it does not make it ALLOWED. Docker Hub meters anonymous pulls
# per source IP, and once the builder's share is spent every pull fails at
# `load metadata` with:
#
#   ERROR: pull access denied ... insufficient_scope: authorization failed
#
# which reads like a missing image rather than a spent quota. An authenticated
# pull draws on the account's much larger allowance instead.
#
# No credentials configured (a fork, a local run) => stay anonymous and say so,
# rather than failing the build for a quota that may well not be spent.
set -eu

if [ -z "${DOCKERHUB_USERNAME:-}" ] || [ -z "${DOCKERHUB_TOKEN:-}" ]; then
  echo "DOCKERHUB_USERNAME/DOCKERHUB_TOKEN unset — pulling Docker Hub anonymously."
  echo "Anonymous pulls share this host's IP quota; a spent quota fails as"
  echo "'insufficient_scope: authorization failed' at 'load metadata' (celilo#1376)."
  exit 0
fi

printf '%s' "${DOCKERHUB_TOKEN}" |
  docker login --username "${DOCKERHUB_USERNAME}" --password-stdin
