#!/bin/bash
# Pulls all external base images the food-market builds depend on, then retags
# them into the local registry at 127.0.0.1:5001 under the "mirror/" prefix.
#
# Why: outbound to docker.io / mcr.microsoft.com flaps on KZ network. Once
# mirrored, Dockerfiles and docker-compose reference the local copy and builds
# no longer need the internet at all.
#
# Idempotent — safe to run as often as you want. Scheduled daily via
# food-market-mirror-base-images.timer.
set -euo pipefail

REGISTRY=127.0.0.1:5001
LOG_PREFIX=$(date -u +%Y-%m-%dT%H:%M:%SZ)

# image_ref → local name under mirror/
IMAGES=(
  "node:20-alpine|mirror/node:20-alpine"
  "nginx:1.27-alpine|mirror/nginx:1.27-alpine"
  "postgres:16-alpine|mirror/postgres:16-alpine"
  "mcr.microsoft.com/dotnet/sdk:8.0|mirror/dotnet-sdk:8.0"
  "mcr.microsoft.com/dotnet/aspnet:8.0|mirror/dotnet-aspnet:8.0"
)

failures=0
for pair in "${IMAGES[@]}"; do
  src="${pair%|*}"
  dst="${pair#*|}"
  echo "$LOG_PREFIX pulling $src"
  if ! docker pull "$src"; then
    echo "$LOG_PREFIX FAILED: pull $src"
    failures=$((failures + 1))
    continue
  fi
  docker tag "$src" "$REGISTRY/$dst"
  if ! docker push "$REGISTRY/$dst"; then
    echo "$LOG_PREFIX FAILED: push $REGISTRY/$dst"
    failures=$((failures + 1))
    continue
  fi
  echo "$LOG_PREFIX ok $src -> $REGISTRY/$dst"
done

if [[ $failures -gt 0 ]]; then
  echo "$LOG_PREFIX done, $failures failed — registry still has old mirrored copies"
  exit 1
fi
echo "$LOG_PREFIX done, all mirrors fresh"
