#!/bin/bash
# Deploy Phase 2 docker-compose files to Phase 1 VMs
# Usage: ./deploy-phase2.sh [region]
# If no region specified, deploys to all regions

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE2_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
TERRAFORM_DIR="${PHASE2_DIR}"
DOCKER_COMPOSE_DIR="$(cd "${PHASE2_DIR}/../../../docker/phase2" && pwd)"

# Region to compose file mapping
declare -A REGION_COMPOSE_MAP=(
  ["centralus"]="docker-compose.cus.yml"
  ["eastus"]="docker-compose.eus.yml"
  ["eastus2"]="docker-compose.eus2.yml"
  ["westus"]="docker-compose.wus.yml"
  ["westus2"]="docker-compose.wus2.yml"
)

REGION="${1:-all}"

echo "Phase 2 Docker Compose Deployment"
echo "================================"
echo ""

cd "${TERRAFORM_DIR}"

if [ "${REGION}" == "all" ]; then
  echo "Deploying to all regions..."
  terraform apply -auto-approve
else
  if [ -z "${REGION_COMPOSE_MAP[${REGION}]}" ]; then
    echo "Error: Invalid region '${REGION}'"
    echo "Valid regions: centralus, eastus, eastus2, westus, westus2"
    exit 1
  fi
  
  echo "Deploying to region: ${REGION}"
  # Terraform doesn't support targeting specific resources in for_each easily
  # Deploy all, but only the specified region will update if it changed
  terraform apply -auto-approve
fi

echo ""
echo "Phase 2 deployment complete!"
echo "Use 'terraform output' to see deployment status and management commands."

