#!/bin/bash
#
# Pre-build all E2E Docker images.
#
# Run once before the test suite. Subsequent test runs use the cached
# images and skip the build phase entirely (~5s vs ~3min per test).
#
# Usage:
#   ./e2e/bin/e2e-build          # build all images
#   ./e2e/bin/e2e-build --save   # build + save to tarball for colima restarts
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
E2E_DIR="$(dirname "$SCRIPT_DIR")"
cd "$E2E_DIR"

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

echo -e "${BOLD}Building E2E Docker images...${NC}"
echo ""

DOCKERFILES=(docker/Dockerfile.*)
TOTAL=${#DOCKERFILES[@]}
START=$(date +%s)

for ((i=0; i<TOTAL; i++)); do
  FILE="${DOCKERFILES[$i]}"
  NAME=$(basename "$FILE" | sed 's/Dockerfile\.//')
  TAG="celilo-e2e/${NAME}"

  printf "  [%d/%d] %-25s " "$((i+1))" "$TOTAL" "$NAME"

  BUILD_START=$(date +%s)
  docker build -t "$TAG" -f "$FILE" . > /dev/null 2>&1
  BUILD_END=$(date +%s)
  DURATION=$((BUILD_END - BUILD_START))

  echo -e "${GREEN}✔${NC} ${DIM}${DURATION}s${NC}"
done

END=$(date +%s)
TOTAL_TIME=$((END - START))
echo ""
echo -e "${GREEN}All $TOTAL images built in ${TOTAL_TIME}s${NC}"

# Optionally save to tarball
if [ "$1" = "--save" ]; then
  echo ""
  echo -e "${BOLD}Saving images to tarball...${NC}"
  TARBALL="$E2E_DIR/.docker-cache/celilo-e2e-images.tar"
  mkdir -p "$(dirname "$TARBALL")"

  IMAGES=$(docker images --filter "reference=celilo-e2e/*" --format "{{.Repository}}:{{.Tag}}" | sort)
  docker save $IMAGES -o "$TARBALL"

  SIZE=$(du -h "$TARBALL" | cut -f1)
  echo -e "${GREEN}Saved to $TARBALL ($SIZE)${NC}"
  echo ""
  echo "To restore after colima restart:"
  echo "  ./e2e/bin/e2e-load"
fi
