#!/bin/bash
#
# Manage the shared E2E infrastructure (DNS, Pebble, apt-cache).
#
# Usage:
#   ./e2e/bin/e2e-infra start   # Start shared infra
#   ./e2e/bin/e2e-infra stop    # Stop shared infra
#   ./e2e/bin/e2e-infra status  # Check if running
#   ./e2e/bin/e2e-infra restart # Restart shared infra
#

set -e

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

SHARED_PROJECT="celilo-e2e-shared"
SHARED_COMPOSE="docker-compose.shared.yml"

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

case "${1:-status}" in
  start)
    echo -e "${BOLD}Starting shared E2E infrastructure...${NC}"

    # Generate compose file
    bun -e "
      import { generateSharedInfraYaml } from './src/docker-compose-generator';
      console.log(generateSharedInfraYaml());
    " > "$SHARED_COMPOSE"

    docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" build
    docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" up -d

    echo -e "${DIM}Waiting for DNS convergence...${NC}"
    for i in $(seq 1 30); do
      DNS=$(docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" exec -T namecheap-dns dig @127.0.0.1 iamtheinternet.org SOA +short +timeout=2 2>/dev/null || true)
      if [ -n "$DNS" ]; then
        echo -e "${GREEN}Shared infrastructure ready${NC}"
        echo ""
        docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" ps --format "  {{.Name}}\t{{.Status}}"
        exit 0
      fi
      sleep 2
    done
    echo -e "${RED}DNS convergence timed out${NC}"
    exit 1
    ;;

  stop)
    echo -e "${BOLD}Stopping shared E2E infrastructure...${NC}"
    docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" down --volumes --remove-orphans 2>/dev/null || true
    docker network prune -f > /dev/null 2>&1 || true
    echo -e "${GREEN}Shared infrastructure stopped${NC}"
    ;;

  restart)
    "$0" stop
    "$0" start
    ;;

  status)
    CONTAINERS=$(docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" ps -q 2>/dev/null || true)
    if [ -n "$CONTAINERS" ]; then
      echo -e "${GREEN}Shared infrastructure is running${NC}"
      echo ""
      docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" ps --format "  {{.Name}}\t{{.Status}}"

      # Health check
      DNS=$(docker compose -f "$SHARED_COMPOSE" -p "$SHARED_PROJECT" exec -T namecheap-dns dig @127.0.0.1 iamtheinternet.org SOA +short +timeout=2 2>/dev/null || true)
      echo ""
      if [ -n "$DNS" ]; then
        echo -e "  DNS: ${GREEN}healthy${NC}"
      else
        echo -e "  DNS: ${RED}unhealthy${NC}"
      fi
    else
      echo -e "${DIM}Shared infrastructure is not running${NC}"
      echo "  Start with: ./e2e/bin/e2e-infra start"
    fi
    ;;

  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac
