#!/bin/bash

# Test host connectivity script
# Tests each host from all_hosts.txt individually

set -uo pipefail

# Load passwords
source secrets/ssh_passwords.env

# Discovery directory
DISCOVERY_DIR="comprehensive_discovery_results"

echo "=== TESTING HOST CONNECTIVITY ==="
echo "Testing each host from: $DISCOVERY_DIR/all_hosts.txt"
echo

# Test each host
while IFS=: read -r host user; do
    if [[ -z "$host" || "$host" == "localhost" ]]; then
        continue
    fi
    
    echo "🔍 Testing: $host (user: $user)"
    
    # Get password for this host
    case "$host" in
        "fedora")
            password="$FEDORA_PASSWORD"
            ;;
        "lenovo")
            password="$LENOVO_PASSWORD"
            ;;
        "lenovo420")
            password="$LENOVO420_PASSWORD"
            ;;
        "omv800")
            password="$OMV800_PASSWORD"
            ;;
        "surface")
            password="$SURFACE_PASSWORD"
            ;;
        "audrey")
            password="$AUDREY_PASSWORD"
            ;;
        "raspberrypi")
            password="$RASPBERRYPI_PASSWORD"
            ;;
        *)
            password=""
            ;;
    esac
    
    if [[ -z "$password" ]]; then
        echo "❌ No password configured for $host"
    else
        echo "   Password: [CONFIGURED]"
        
        # Test SSH connection
        if sshpass -p "$password" ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$user@$host" "echo 'SSH connection successful'" 2>/dev/null; then
            echo "✅ SSH: SUCCESS"
            
            # Test basic commands
            echo "   Testing basic commands..."
            if sshpass -p "$password" ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$user@$host" "hostname && whoami && pwd" 2>/dev/null; then
                echo "✅ Commands: SUCCESS"
            else
                echo "❌ Commands: FAILED"
            fi
        else
            echo "❌ SSH: FAILED"
        fi
    fi
    
    echo "---"
done < "$DISCOVERY_DIR/all_hosts.txt"

echo "=== CONNECTIVITY TEST COMPLETE ==="
