#!/bin/bash
set -e  # Exit immediately if a command exits with a non-zero status

# Absolute path to the docker-compose file
COMPOSE_FILE="/home/prowatchlyadmin/prowatchly/prowatchlyAppSetup/compose.deploy.yml"

# Log output to a file (uncomment to enable)
# exec > >(tee -i deployment.log) 2>&1

echo "Pulling images from Docker Hub..."
docker-compose -f "$COMPOSE_FILE" pull

# Check if update_trigger_fapi is already running
if docker ps --filter "name=update_trigger_fapi" --filter "status=running" | grep -q update_trigger_fapi; then
    echo "update_trigger_fapi is already running. Skipping redeployment for this service."
    exclude_service_flag=true
else
    echo "update_trigger_fapi is not running. Including it in the deployment."
    exclude_service_flag=false
fi

# Check if any containers from this specific docker-compose project are running
running_containers=$(docker-compose -f "$COMPOSE_FILE" ps -q)

if [ -z "$running_containers" ]; then
    # First-time setup: No containers from this compose file are running
    echo "No running containers found from this compose file. Starting all containers for the first time..."
    docker-compose -f "$COMPOSE_FILE" up -d --remove-orphans
else
    # Not the first time: Stop and remove old containers except for update_trigger_fapi
    echo "Stopping and removing old containers (excluding update_trigger_fapi)..."
    if [ "$exclude_service_flag" = true ]; then
        # Stop and remove all services except update_trigger_fapi
        docker-compose -f "$COMPOSE_FILE" stop $(docker-compose -f "$COMPOSE_FILE" config --services | grep -v update_trigger_fapi)
        docker-compose -f "$COMPOSE_FILE" rm -f $(docker-compose -f "$COMPOSE_FILE" config --services | grep -v update_trigger_fapi)

        echo "Starting containers (excluding update_trigger_fapi)..."
        docker-compose -f "$COMPOSE_FILE" up -d --remove-orphans $(docker-compose -f "$COMPOSE_FILE" config --services | grep -v update_trigger_fapi)
    else
        # If update_trigger_fapi is running, just bring up the containers
        docker-compose -f "$COMPOSE_FILE" up -d --remove-orphans
    fi
fi

echo "Deployment completed!"
