#!/bin/bash
#
# Save application Docker images to the local cache for e2e acceleration.
#
# The cached tarballs are mounted into app-zone target machines and
# pre-loaded at startup, avoiding slow pulls from ghcr.io / docker.io
# during every test run.
#
# Run once after pulling new image versions. The cache directory is
# gitignored — each developer maintains their own copy.
#
# Usage:
#   ./e2e/bin/e2e-cache-images
#

set -e

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

mkdir -p "$CACHE_DIR"

BOLD='\033[1m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
DIM='\033[2m'
NC='\033[0m'

# Images used by deployed modules in the app zone.
# Update versions here when bumping module image versions.
declare -A IMAGES=(
  ["docker.io_library_postgres_15-alpine"]="docker.io/library/postgres:15-alpine"
  ["docker.io_library_redis_alpine"]="docker.io/library/redis:alpine"
  ["ghcr.io_goauthentik_server_2024.2.2"]="ghcr.io/goauthentik/server:2024.2.2"
)

echo -e "${BOLD}Pulling and caching application images...${NC}"
echo ""

for filename in "${!IMAGES[@]}"; do
  image="${IMAGES[$filename]}"
  tarball="$CACHE_DIR/${filename}.tar"

  printf "  %-50s " "$image"
  START=$(date +%s)

  # Per-image best-effort: a transient registry failure for one image must not
  # abort caching the others (this runs inside build-infra now). A guarded
  # command does not trip `set -e`. The preload service skips a missing tarball
  # gracefully — that module just pulls over the sim at deploy time.
  if docker pull "$image" > /dev/null 2>&1 && docker save "$image" -o "$tarball"; then
    END=$(date +%s)
    SIZE=$(du -h "$tarball" | cut -f1)
    echo -e "${GREEN}✔${NC} ${DIM}$((END - START))s  ${SIZE}${NC}"
  else
    rm -f "$tarball"
    echo -e "${YELLOW}✘ failed — will pull over the sim at deploy time${NC}"
  fi
done

echo ""
echo -e "${GREEN}Images cached to $CACHE_DIR${NC}"
echo "These will be pre-loaded into app-zone containers on next e2e run."
