#!/bin/bash

# Load environment variables from .env if it exists
if [ -f .env ]; then
  export $(grep -v '^#' .env | xargs)
fi

# Check if 'docker compose' (v2) or 'docker-compose' (v1) is available
if docker compose version >/dev/null 2>&1; then
    COMPOSE_CMD="docker compose"
elif docker-compose version >/dev/null 2>&1; then
    COMPOSE_CMD="docker-compose"
else
    echo "❌ Error: Docker Compose not found. Please install Docker Compose first."
    exit 1
fi

# Name of the database container
DB_CONTAINER_NAME="portfolio-db"

# Check if the database container is already running
if [ "$(docker ps -q -f name=${DB_CONTAINER_NAME})" ]; then
    echo "✅ Database container '${DB_CONTAINER_NAME}' is already running."
    echo "🚀 Deploying/Updating only the application..."
    $COMPOSE_CMD up -d --no-recreate db
    $COMPOSE_CMD up -d app
else
    echo "⚠️ Database container '${DB_CONTAINER_NAME}' not found or stopped."
    echo "🏗️ Deploying full stack (Database + App)..."
    $COMPOSE_CMD up -d
fi

echo "✨ Deployment script finished!"
