#!/bin/bash
set -e

# The credentials come from DOCKER_REGISTRY_USER / DOCKER_REGISTRY_PASSWORD,
# which the deploy job resolves per CI backend (gitlab: CI_REGISTRY_USER +
# CI_REGISTRY_PASSWORD, github: the actor + workflow token) — the raw
# gitlab names used to be hardcoded here, which left the secret without
# credentials on the github backend.
#
# Both of those are job-scoped and expire with the pipeline: the initial
# pull works, but a pod rescheduled later can no longer re-pull. Projects
# that need durable pulls declare long-lived registry credentials as
# secrets named CI_DEPLOY_USER / CI_DEPLOY_PASSWORD, which win here.
#
# --docker-email is deliberately gone: it is optional for a
# docker-registry secret and its only source was $GITLAB_USER_EMAIL.
echo "KUBE_NAMESPACE: '$KUBE_NAMESPACE', KUBE_DOCKER_IMAGE_PULL_SECRET: '$KUBE_DOCKER_IMAGE_PULL_SECRET'"
kubectl create secret -n "$KUBE_NAMESPACE" \
    docker-registry $KUBE_DOCKER_IMAGE_PULL_SECRET \
    --docker-server="$DOCKER_REGISTRY" \
    --docker-username="${CI_DEPLOY_USER:-$DOCKER_REGISTRY_USER}" \
    --docker-password="${CI_DEPLOY_PASSWORD:-$DOCKER_REGISTRY_PASSWORD}" \
    -o yaml --dry-run | kubectl replace -n "$KUBE_NAMESPACE" --force -f -
