#!/bin/bash
# View core_room logs
#
# Usage:
#   ./logs.sh              # All logs
#   ./logs.sh <service>    # Service compose logs (e.g., amar, soleprint)
#   ./logs.sh <container>  # Specific container name (e.g., backend, db)

set -e

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

# Export core_room/.env vars
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

# ROOM_NAME comes from core_room/.env
ROOM_NAME=${ROOM_NAME:-core_room}

if [[ " ${SERVICE_DIRS[@]} " =~ " ${TARGET} " ]]; then
    # Service directory logs
    cd "$TARGET" && docker compose logs -f
elif [ "$TARGET" = "all" ]; then
    # All containers matching ROOM_NAME
    docker logs -f $(docker ps -q --filter "name=${ROOM_NAME}") 2>/dev/null || \
    echo "No ${ROOM_NAME} containers running"
else
    # Specific container name
    docker logs -f "${ROOM_NAME}_$TARGET" 2>/dev/null || \
    docker logs -f "$TARGET" 2>/dev/null || \
    echo "Container not found: $TARGET"
fi
