#!/bin/bash
# Stop Phase 2 docker-compose services on VMs
# Usage: ./stop-services.sh [region]
# If no region specified, stops services on all regions

set -e

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

REGION="${1:-all}"

echo "Stopping Phase 2 Docker Compose Services"
echo "========================================"
echo ""

cd "${TERRAFORM_DIR}"

# Get VM information from Terraform outputs
MANAGEMENT_CMDS=$(terraform output -json management_commands 2>/dev/null || echo "{}")

if [ "${REGION}" == "all" ]; then
  echo "Stopping services on all regions in parallel..."
  
  # Store PIDs for parallel execution
  declare -A PIDS
  
  for region in $(echo "${MANAGEMENT_CMDS}" | jq -r 'keys[]'); do
    ssh_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].ssh_connection")
    stop_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].stop_service")
    
    host=$(echo "${ssh_cmd}" | awk '{print $2}' | cut -d'@' -f2)
    user=$(echo "${ssh_cmd}" | awk '{print $2}' | cut -d'@' -f1)
    
    if [ -n "${host}" ] && [ "${host}" != "null" ] && [ "${host}" != "N/A" ]; then
      (
        echo "[${region}] Stopping services..."
        if ssh "${user}@${host}" "sudo systemctl stop phase2-stack.service" 2>&1; then
          echo "[${region}] ✓ Services stopped successfully"
        else
          echo "[${region}] ✗ Failed to stop services"
        fi
      ) &
      PIDS["${region}"]=$!
    else
      echo "[${region}] ✗ Could not determine host"
    fi
  done
  
  # Wait for all parallel operations to complete
  FAILED=0
  for region in "${!PIDS[@]}"; do
    wait "${PIDS[$region]}" || ((FAILED++))
  done
  
  if [ $FAILED -gt 0 ]; then
    echo ""
    echo "⚠️  ${FAILED} region(s) failed to stop services"
    exit 1
  fi
  
  echo ""
  echo "✓ All regions stopped in parallel"
else
  ssh_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${REGION}\"].ssh_connection // empty")
  
  if [ -z "${ssh_cmd}" ] || [ "${ssh_cmd}" == "null" ]; then
    echo "Error: Region '${REGION}' not found in Terraform outputs"
    exit 1
  fi
  
  echo "Stopping services on ${REGION}..."
  host=$(echo "${ssh_cmd}" | awk '{print $2}' | cut -d'@' -f2)
  user=$(echo "${ssh_cmd}" | awk '{print $2}' | cut -d'@' -f1)
  
  ssh "${user}@${host}" "sudo systemctl stop phase2-stack.service"
  echo "✓ Services stopped on ${REGION}"
fi

echo ""
echo "Services stopped successfully!"

