#!/bin/bash
# Stop core_room services
#
# Usage:
#   ./stop.sh          # Stop all
#   ./stop.sh <service> # Stop specific service

set -e

# Change to parent directory (services are in ../service_name)
cd "$(dirname "$0")/.."

# Export core_room/.env vars so child docker-compose files can use them
if [ -f ".env" ]; then
    export $(grep -v '^#' .env | grep -v '^$' | xargs)
fi

TARGET=${1:-all}
SERVICE_DIRS=()

# Find all service directories (have docker-compose.yml, exclude ctrl/nginx)
for dir in */; do
    dirname="${dir%/}"
    if [ -f "$dir/docker-compose.yml" ] && [ "$dirname" != "ctrl" ] && [ "$dirname" != "nginx" ]; then
        SERVICE_DIRS+=("$dirname")
    fi
done

stop_service() {
    local service=$1
    echo "Stopping $service..."
    cd "$service"
    docker compose down
    cd ..
}

if [ "$TARGET" = "all" ]; then
    # Stop all services in reverse order (dependencies first)
    for ((i=${#SERVICE_DIRS[@]}-1; i>=0; i--)); do
        stop_service "${SERVICE_DIRS[$i]}"
    done
elif [[ " ${SERVICE_DIRS[@]} " =~ " ${TARGET} " ]]; then
    stop_service "$TARGET"
else
    echo "Usage: ./stop.sh [${SERVICE_DIRS[*]}|all]"
    exit 1
fi

echo ""
echo "=== Services Stopped ==="
