#!/bin/bash

# Define variables
DOCKER_USERNAME="medkaddour"
SERVICES=("camera" "motion_detector" "object_recognizer")
TAG="latest"
DEPLOY_ENV=${1:-local}  # Default to 'cloud' if no argument is provided

# Function to build and push a Docker image
build_and_push() {
  local service=$1
  local service_path="./services/${service}"  # Service directory path
  echo "Building Docker image for ${service} from ${service_path}..."
  docker build -t ${DOCKER_USERNAME}/${service}:${TAG} ${service_path}

  if [ "$DEPLOY_ENV" == "cloud" ]; then
    echo "Pushing Docker image for ${service} to Docker Hub..."
    docker push ${DOCKER_USERNAME}/${service}:${TAG}
  fi
}

# Step 1: Build Docker images for all services
for service in "${SERVICES[@]}"; do
  build_and_push ${service}
done

# Step 2: Deploy the images
DOCKER_COMPOSE_PATH="./deploy/docker-compose/docker-compose.yml"
if [ "$DEPLOY_ENV" == "local" ]; then
  echo "Stopping and removing existing containers..."
  docker-compose -f ${DOCKER_COMPOSE_PATH} down --volumes --remove-orphans
  echo "Running Docker images locally with Docker Compose..."
  docker-compose -f ${DOCKER_COMPOSE_PATH} up -d --build --force-recreate
elif [ "$DEPLOY_ENV" == "cloud" ]; then
  echo "Stopping and removing existing containers..."
  docker-compose -f ${DOCKER_COMPOSE_PATH} down --volumes --remove-orphans
  echo "Pulling and running Docker images from Docker Hub with Docker Compose..."
  # Force repull the latest images
  docker-compose -f ${DOCKER_COMPOSE_PATH} pull --ignore-pull-failures
  docker-compose -f ${DOCKER_COMPOSE_PATH} up -d --build --force-recreate
else
  echo "Invalid DEPLOY_ENV value. Please use 'local' or 'cloud'."
  exit 1
fi

echo "Deployment completed."
