#!/bin/bash
#
# Pre-build all E2E Docker images and package standard modules as .netapps.
#
# 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 netapps + 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")"
PKG_DIR="$E2E_DIR"
REPO_ROOT="$(cd "$E2E_DIR/../.." && pwd)"
MODULES_DIR="$REPO_ROOT/modules"
NETAPPS_DIR="$E2E_DIR/netapps"

cd "$E2E_DIR"

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

# ── Step 1: Package standard modules as .netapp files ─────────────────────────

STANDARD_MODULES=(namecheap greenwave iptables caddy authentik)

echo -e "${BOLD}Packaging standard modules...${NC}"
echo ""

mkdir -p "$NETAPPS_DIR"

for MODULE in "${STANDARD_MODULES[@]}"; do
  SRC="$MODULES_DIR/$MODULE"
  OUT="$NETAPPS_DIR/$MODULE.netapp"

  if [ ! -d "$SRC" ]; then
    echo -e "  ${DIM}skip${NC}  $MODULE  ${DIM}(not found at $SRC)${NC}"
    continue
  fi

  printf "  %-20s " "$MODULE"
  BUILD_START=$(date +%s)

  # Use the wrapper script if available, else bun directly
  if [ -x "$REPO_ROOT/celilo" ]; then
    "$REPO_ROOT/celilo" package "$SRC" --output "$OUT" > /dev/null 2>&1
  else
    bun run "$REPO_ROOT/apps/celilo/src/cli/index.ts" package "$SRC" --output "$OUT" > /dev/null 2>&1
  fi

  BUILD_END=$(date +%s)
  SIZE=$(du -h "$OUT" 2>/dev/null | cut -f1)
  echo -e "${GREEN}✔${NC} ${DIM}$((BUILD_END - BUILD_START))s  ${SIZE}${NC}"
done

echo ""

# ── Step 2: Build Docker images ───────────────────────────────────────────────

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}"

# ── Step 3: Optionally save images 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
