#!/bin/bash
# Check Phase 2 docker-compose services status on VMs
# Usage: ./status.sh [region]
# If no region specified, checks status 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 "Phase 2 Docker Compose Services Status"
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 "Checking status on all regions in parallel..."
  echo ""
  
  # Store PIDs and output files for parallel execution
  declare -A PIDS
  TEMP_DIR=$(mktemp -d)
  
  for region in $(echo "${MANAGEMENT_CMDS}" | jq -r 'keys[]'); do
    ssh_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].ssh_connection")
    status_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].status_service")
    compose_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${region}\"].docker_compose")
    
    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
      (
        OUTPUT_FILE="${TEMP_DIR}/${region}.out"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" > "$OUTPUT_FILE"
        echo "Region: ${region}" >> "$OUTPUT_FILE"
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" >> "$OUTPUT_FILE"
        echo "" >> "$OUTPUT_FILE"
        
        echo "Systemd Service Status:" >> "$OUTPUT_FILE"
        ssh "${user}@${host}" "sudo systemctl status phase2-stack.service --no-pager -l" >> "$OUTPUT_FILE" 2>&1 || echo "Service status check failed" >> "$OUTPUT_FILE"
        echo "" >> "$OUTPUT_FILE"
        
        echo "Docker Compose Status:" >> "$OUTPUT_FILE"
        ssh "${user}@${host}" "cd /opt/docker-compose && docker compose ps" >> "$OUTPUT_FILE" 2>&1 || echo "Docker compose status check failed" >> "$OUTPUT_FILE"
        echo "" >> "$OUTPUT_FILE"
      ) &
      PIDS["${region}"]=$!
    else
      echo "[${region}] ✗ Could not determine host"
    fi
  done
  
  # Wait for all parallel operations to complete
  for region in "${!PIDS[@]}"; do
    wait "${PIDS[$region]}"
  done
  
  # Display results in order
  for region in $(echo "${MANAGEMENT_CMDS}" | jq -r 'keys[]'); do
    if [ -f "${TEMP_DIR}/${region}.out" ]; then
      cat "${TEMP_DIR}/${region}.out"
    fi
  done
  
  # Cleanup
  rm -rf "$TEMP_DIR"
else
  ssh_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${REGION}\"].ssh_connection // empty")
  status_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${REGION}\"].status_service // empty")
  compose_cmd=$(echo "${MANAGEMENT_CMDS}" | jq -r ".[\"${REGION}\"].docker_compose // empty")
  
  if [ -z "${ssh_cmd}" ] || [ "${ssh_cmd}" == "null" ]; then
    echo "Error: Region '${REGION}' not found in Terraform outputs"
    exit 1
  fi
  
  echo "Checking status on ${REGION}..."
  echo ""
  host=$(echo "${ssh_cmd}" | awk '{print $2}' | cut -d'@' -f2)
  user=$(echo "${ssh_cmd}" | awk '{print $2}' | cut -d'@' -f1)
  
  echo "Systemd Service Status:"
  ssh "${user}@${host}" "sudo systemctl status phase2-stack.service --no-pager -l"
  echo ""
  echo "Docker Compose Status:"
  ssh "${user}@${host}" "cd /opt/docker-compose && docker compose ps"
fi

echo ""
echo "Status check complete!"

