#!/bin/bash
# VM Connectivity Testing Script
# Tests SSH and service connectivity to VMs

set -euo pipefail

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

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "=========================================="
echo "VM Connectivity Testing"
echo "=========================================="
echo ""

cd "$PHASE1_DIR"

# Get Nginx proxy IP
NGINX_IP=$(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value.public_ip // empty' || echo "")
NGINX_PRIVATE_IP=$(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value.private_ip // empty' || echo "")

if [ -n "$NGINX_IP" ] && [ "$NGINX_IP" != "null" ]; then
    echo -e "${BLUE}Nginx Proxy:${NC} $NGINX_IP (public) / $NGINX_PRIVATE_IP (private)"
    echo ""
    
    # Test SSH
    echo "Testing SSH connectivity..."
    if timeout 5 bash -c "echo > /dev/tcp/$NGINX_IP/22" 2>/dev/null; then
        echo -e "${GREEN}✓${NC} SSH port (22) is open"
        
        # Try actual SSH connection (non-interactive)
        if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -o BatchMode=yes besuadmin@$NGINX_IP "echo 'SSH connection successful'" 2>/dev/null; then
            echo -e "${GREEN}✓${NC} SSH authentication successful"
        else
            echo -e "${YELLOW}⊘${NC} SSH port open but authentication required (expected)"
        fi
    else
        echo -e "${RED}✗${NC} SSH port (22) not accessible"
    fi
    
    # Test HTTP/HTTPS
    echo ""
    echo "Testing HTTP/HTTPS connectivity..."
    if timeout 5 bash -c "echo > /dev/tcp/$NGINX_IP/80" 2>/dev/null; then
        echo -e "${GREEN}✓${NC} HTTP port (80) is open"
        HTTP_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 "http://$NGINX_IP" 2>/dev/null || echo "000")
        if [ "$HTTP_RESPONSE" != "000" ]; then
            echo -e "${GREEN}✓${NC} HTTP responds with status: $HTTP_RESPONSE"
        fi
    else
        echo -e "${YELLOW}⊘${NC} HTTP port (80) not accessible (Nginx may not be configured)"
    fi
    
    if timeout 5 bash -c "echo > /dev/tcp/$NGINX_IP/443" 2>/dev/null; then
        echo -e "${GREEN}✓${NC} HTTPS port (443) is open"
    else
        echo -e "${YELLOW}⊘${NC} HTTPS port (443) not accessible (SSL not configured)"
    fi
else
    echo -e "${RED}✗${NC} Nginx proxy IP not found"
fi

# Test Backend VMs
echo ""
echo "=========================================="
echo "Backend VM Connectivity"
echo "=========================================="
echo ""

BACKEND_VMS=$(terraform output -json 2>/dev/null | jq -r '.phase1_us_regions.value | to_entries[] | "\(.key):\(.value.private_ips[0])"' || echo "")

if [ -n "$BACKEND_VMS" ]; then
    while IFS=: read -r region ip; do
        if [ -n "$ip" ] && [ "$ip" != "null" ]; then
            echo -e "${BLUE}Region: $region${NC} - IP: $ip"
            
            # Test SSH (will likely fail without VPN)
            if timeout 3 bash -c "echo > /dev/tcp/$ip/22" 2>/dev/null; then
                echo -e "  ${GREEN}✓${NC} SSH port (22) accessible"
            else
                echo -e "  ${YELLOW}⊘${NC} SSH port (22) requires VPN/Bastion (expected for private IPs)"
            fi
            
            # Test RPC ports
            if timeout 3 bash -c "echo > /dev/tcp/$ip/8545" 2>/dev/null; then
                echo -e "  ${GREEN}✓${NC} RPC HTTP (8545) accessible"
            else
                echo -e "  ${YELLOW}⊘${NC} RPC HTTP (8545) not accessible (Besu may not be running)"
            fi
            
            if timeout 3 bash -c "echo > /dev/tcp/$ip/8546" 2>/dev/null; then
                echo -e "  ${GREEN}✓${NC} RPC WebSocket (8546) accessible"
            else
                echo -e "  ${YELLOW}⊘${NC} RPC WebSocket (8546) not accessible"
            fi
            
            if timeout 3 bash -c "echo > /dev/tcp/$ip/9545" 2>/dev/null; then
                echo -e "  ${GREEN}✓${NC} Metrics (9545) accessible"
            else
                echo -e "  ${YELLOW}⊘${NC} Metrics (9545) not accessible"
            fi
            
            echo ""
        fi
    done <<< "$BACKEND_VMS"
else
    echo -e "${RED}✗${NC} Backend VMs not found"
fi

echo "=========================================="
echo "Connectivity Test Complete"
echo "=========================================="

