#!/bin/bash
# Tear down ALL E2E test artifacts — interactive sessions AND orphaned test runs.
#
# Usage:
#   ./bin/e2e-down           # Stop and remove everything
#   ./bin/e2e-down --keep    # Stop containers but keep volumes (faster restart)
#   ./bin/e2e-down --all     # Also stop module containers (authentik, etc.) that compete for resources

set -e
SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$SCRIPT_DIR"

KEEP_VOLUMES=false
STOP_ALL=false
for arg in "$@"; do
  case "$arg" in
    --keep) KEEP_VOLUMES=true ;;
    --all) STOP_ALL=true ;;
  esac
done

# 1. Stop the interactive session (if running)
echo "Stopping interactive session..."
docker compose -p "conductor-e2e-interactive" down --remove-orphans 2>/dev/null || true

# 2. Kill ALL containers matching conductor-e2e-* (orphaned test runs)
CONTAINERS=$(docker ps -a --filter "name=conductor-e2e" --format "{{.ID}}" 2>/dev/null)
if [ -n "$CONTAINERS" ]; then
  COUNT=$(echo "$CONTAINERS" | wc -l | tr -d ' ')
  echo "Removing $COUNT orphaned e2e containers..."
  echo "$CONTAINERS" | xargs docker rm -f 2>/dev/null || true
fi

# 3. Stop module containers that compete for resources (--all flag)
# These come from local docker-compose runs, not from e2e, but starve the VM.
if [ "$STOP_ALL" = true ]; then
  MODULE_PATTERNS="authentik- caddy- build-your-own-internet-"
  for pattern in $MODULE_PATTERNS; do
    MODULE_CONTAINERS=$(docker ps -a --filter "name=$pattern" --format "{{.ID}}" 2>/dev/null)
    if [ -n "$MODULE_CONTAINERS" ]; then
      COUNT=$(echo "$MODULE_CONTAINERS" | wc -l | tr -d ' ')
      echo "Stopping $COUNT containers matching '$pattern*'..."
      echo "$MODULE_CONTAINERS" | xargs docker rm -f 2>/dev/null || true
    fi
  done
fi

# 3. Remove all conductor-e2e networks
NETWORKS=$(docker network ls --filter "name=conductor-e2e" --format "{{.ID}}" 2>/dev/null)
if [ -n "$NETWORKS" ]; then
  echo "Removing e2e networks..."
  echo "$NETWORKS" | xargs docker network rm 2>/dev/null || true
fi

# 4. Remove volumes (unless --keep)
if [ "$KEEP_VOLUMES" = false ]; then
  VOLUMES=$(docker volume ls --filter "name=conductor-e2e" --format "{{.Name}}" 2>/dev/null)
  if [ -n "$VOLUMES" ]; then
    echo "Removing e2e volumes..."
    echo "$VOLUMES" | xargs docker volume rm 2>/dev/null || true
  fi
fi

# 5. Clean up generated compose file
rm -f docker-compose.test.yml

echo "E2E environment cleaned."
