#!/bin/bash
# Start Phase 2 docker-compose services on VMs
# Usage: ./start-services.sh [region] [vm_index]
# If no region specified, starts services on all regions
# vm_index defaults to 0 (first VM in region)

set -e

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

REGION="${1:-all}"
VM_INDEX="${2:-0}"

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

cd "${TERRAFORM_DIR}"

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

if [ "${REGION}" == "all" ]; then
  echo "Starting services on all regions in parallel..."
  
  # Store PIDs for parallel execution
  declare -A PIDS
  
  for region in $(echo "${VM_INFO}" | jq -r 'keys[]'); do
    ssh_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].ssh_connection")
    start_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].start_service")
    
    # Extract host from SSH command
    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}] Starting services..."
        if ssh "${user}@${host}" "sudo systemctl start phase2-stack.service" 2>&1; then
          echo "[${region}] ✓ Services started successfully"
        else
          echo "[${region}] ✗ Failed to start 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 start services"
    exit 1
  fi
  
  echo ""
  echo "✓ All regions started in parallel"
else
  ssh_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${REGION}\"].ssh_connection // empty")
  start_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${REGION}\"].start_service // empty")
  
  if [ -z "${ssh_cmd}" ] || [ "${ssh_cmd}" == "null" ]; then
    echo "Error: Region '${REGION}' not found in Terraform outputs"
    echo "Run 'terraform apply' first or check your Phase 1 deployment"
    exit 1
  fi
  
  echo "Starting 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 start phase2-stack.service"
  echo "✓ Services started on ${REGION}"
fi

echo ""
echo "Services started successfully!"

