#!/usr/bin/env bash
#
# Pre-pull and save Docker images needed by e2e test modules.
# Saves them as tarballs that get mounted into app-zone containers
# for fast loading at boot time.
#
# Run this once (or after updating image versions) to populate the cache.
# Images are stored in e2e/docker-image-cache/

set -e

CACHE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/docker-image-cache"
mkdir -p "$CACHE_DIR"

IMAGES=(
  "docker.io/library/postgres:15-alpine"
  "docker.io/library/redis:alpine"
  "ghcr.io/goauthentik/server:2024.2.2"
)

echo "Caching Docker images for e2e tests..."
echo "Cache directory: $CACHE_DIR"
echo ""

for image in "${IMAGES[@]}"; do
  # Create a safe filename from the image name
  filename=$(echo "$image" | sed 's|[/:]|_|g').tar

  if [[ -f "$CACHE_DIR/$filename" ]]; then
    echo "✓ $image (already cached)"
    continue
  fi

  echo "▸ Pulling $image..."
  docker pull "$image"

  echo "  Saving to $filename..."
  docker save "$image" > "$CACHE_DIR/$filename"

  size=$(du -h "$CACHE_DIR/$filename" | cut -f1)
  echo "✓ $image ($size)"
done

echo ""
echo "Cache complete. $(ls "$CACHE_DIR"/*.tar 2>/dev/null | wc -l | tr -d ' ') images cached."
echo "Total size: $(du -sh "$CACHE_DIR" | cut -f1)"
