#!/bin/bash
# Mirror upstream Docker images to GitLab Container Registry
# Run manually or via scheduled GitLab pipeline
# This avoids Docker Hub rate limits and ensures build reliability

set -euo pipefail

REGISTRY="${REGISTRY:-git.motovaultpro.com/egullickson/mirrors}"

# Base images required by MotoVaultPro
IMAGES=(
  "node:20-alpine"
  "nginx:alpine"
  "postgres:18-alpine"
  "redis:8.4-alpine"
  "traefik:v3.6"
  "python:3.13-slim"
  "grafana/loki:3.6.1"
  "grafana/alloy:v1.12.2"
  "grafana/grafana:12.4.0-21693836646"
)

echo "========================================"
echo "Base Image Mirroring Script"
echo "Registry: $REGISTRY"
echo "========================================"

# Check if logged into registry
if ! docker info 2>/dev/null | grep -q "Username"; then
  echo "WARNING: Not logged into Docker registry"
  echo "Run: docker login registry.motovaultpro.com"
fi

FAILED=()
SUCCESS=()

for img in "${IMAGES[@]}"; do
  echo ""
  echo "Processing: $img"
  echo "----------------------------------------"

  # Pull from upstream
  echo "  Pulling from upstream..."
  if ! docker pull "$img"; then
    echo "  ERROR: Failed to pull $img"
    FAILED+=("$img")
    continue
  fi

  # Tag for local registry
  local_tag="$REGISTRY/$img"
  echo "  Tagging as: $local_tag"
  docker tag "$img" "$local_tag"

  # Push to local registry
  echo "  Pushing to registry..."
  if ! docker push "$local_tag"; then
    echo "  ERROR: Failed to push $local_tag"
    FAILED+=("$img")
    continue
  fi

  SUCCESS+=("$img")
  echo "  OK: $img mirrored successfully"
done

echo ""
echo "========================================"
echo "Summary"
echo "========================================"
echo "Successful: ${#SUCCESS[@]}"
for img in "${SUCCESS[@]}"; do
  echo "  - $img"
done

if [ ${#FAILED[@]} -gt 0 ]; then
  echo ""
  echo "Failed: ${#FAILED[@]}"
  for img in "${FAILED[@]}"; do
    echo "  - $img"
  done
  exit 1
fi

echo ""
echo "All images mirrored successfully"
