#!/bin/bash
# Connect to a running E2E container.
#
# Usage:
#   ./bin/e2e-shell                # Shell into management (interactive or test project)
#   ./bin/e2e-shell caddy          # Shell into caddy container
#   ./bin/e2e-shell authentik      # Shell into authentik container (test project)

set -e
CONTAINER="${1:-management}"

# Resolve project name: prefer interactive project, fall back to any running test project
resolve_project() {
  # 1. Interactive project (e2e-up)
  if docker compose -p celilo-e2e-interactive ps --status running 2>/dev/null | grep -q "$CONTAINER"; then
    echo "celilo-e2e-interactive"
    return
  fi

  # 2. Test run project: find any celilo-e2e-* container matching the name
  local container_id
  container_id=$(docker ps --filter "name=${CONTAINER}" --filter "name=celilo-e2e-" --format '{{.Names}}' | head -1)
  if [ -n "$container_id" ]; then
    # Extract project from container name: celilo-e2e-<project>-<service>-1
    # We don't need the compose project name — just exec directly
    echo "_direct:${container_id}"
    return
  fi

  echo ""
}

PROJECT=$(resolve_project)

if [ -z "$PROJECT" ]; then
  echo "Container '$CONTAINER' is not running in any celilo-e2e project."
  echo ""
  echo "Running celilo-e2e containers:"
  docker ps --filter "name=celilo-e2e-" --format '  {{.Names}}  ({{.Status}})' 2>/dev/null || echo "  none"
  exit 1
fi

SHELL_CMD="bash"

if [[ "$PROJECT" == _direct:* ]]; then
  FULL_NAME="${PROJECT#_direct:}"
  exec docker exec -it "$FULL_NAME" $SHELL_CMD
else
  exec docker compose -p "$PROJECT" exec "$CONTAINER" $SHELL_CMD
fi
