#!/bin/bash
# Redis connectivity test for Captain/production environments
# This script tests basic network connectivity to Redis

echo "🔍 Redis Connectivity Test for Captain"
echo "======================================"
echo ""

# Extract values from REDIS_URL if set
if [ -n "$REDIS_URL" ]; then
    echo "REDIS_URL is set: $REDIS_URL"
    
    # Parse the URL to extract host and port
    # Format: redis://[username]:[password]@[host]:[port]
    REDIS_HOST=$(echo $REDIS_URL | sed -n 's/.*@\([^:]*\).*/\1/p')
    REDIS_PORT=$(echo $REDIS_URL | sed -n 's/.*:\([0-9]*\)$/\1/p')
    
    if [ -z "$REDIS_PORT" ]; then
        REDIS_PORT="6379"
    fi
    
    echo "Parsed host: $REDIS_HOST"
    echo "Parsed port: $REDIS_PORT"
else
    echo "❌ REDIS_URL environment variable not set"
    echo "Please set REDIS_URL before running this test"
    exit 1
fi

echo ""
echo "📋 Running connectivity tests..."
echo ""

# Test 1: DNS resolution
echo "⏳ Test 1: DNS Resolution"
if host $REDIS_HOST > /dev/null 2>&1; then
    IP=$(host $REDIS_HOST | awk '/has address/ { print $4 }' | head -n 1)
    echo "✅ DNS resolved: $REDIS_HOST -> $IP"
else
    echo "❌ DNS resolution failed for $REDIS_HOST"
    echo "   This host cannot be found. Check:"
    echo "   - Is the hostname correct?"
    echo "   - Is DNS configured properly?"
    exit 1
fi

echo ""

# Test 2: Ping (if available)
echo "⏳ Test 2: Ping Test"
if ping -c 3 -W 2 $REDIS_HOST > /dev/null 2>&1; then
    echo "✅ Host is reachable via ping"
else
    echo "⚠️  Ping failed or ICMP blocked (this is often normal)"
    echo "   Continuing with port tests..."
fi

echo ""

# Test 3: Port connectivity
echo "⏳ Test 3: TCP Port Connectivity"
if command -v nc > /dev/null 2>&1; then
    if nc -zv -w 3 $REDIS_HOST $REDIS_PORT 2>&1 | grep -q succeeded; then
        echo "✅ Port $REDIS_PORT is open and accepting connections"
    else
        echo "❌ Cannot connect to port $REDIS_PORT on $REDIS_HOST"
        echo "   Possible issues:"
        echo "   - Redis is not running"
        echo "   - Firewall blocking port $REDIS_PORT"
        echo "   - Redis not configured to accept remote connections"
        echo "   - Wrong host or port in REDIS_URL"
        exit 1
    fi
elif command -v timeout > /dev/null 2>&1; then
    if timeout 3 bash -c "cat < /dev/null > /dev/tcp/$REDIS_HOST/$REDIS_PORT" 2>/dev/null; then
        echo "✅ Port $REDIS_PORT is open and accepting connections"
    else
        echo "❌ Cannot connect to port $REDIS_PORT on $REDIS_HOST"
        exit 1
    fi
else
    echo "⚠️  netcat (nc) not available, cannot test port connectivity"
fi

echo ""

# Test 4: Redis PING using redis-cli if available
echo "⏳ Test 4: Redis Protocol Test"
if command -v redis-cli > /dev/null 2>&1; then
    if [ -n "$REDIS_PASSWORD" ]; then
        if redis-cli -h $REDIS_HOST -p $REDIS_PORT -a "$REDIS_PASSWORD" --no-auth-warning ping 2>&1 | grep -q PONG; then
            echo "✅ Redis PING successful (with authentication)"
        else
            echo "❌ Redis PING failed with authentication"
            echo "   Check if password is correct"
            exit 1
        fi
    else
        if redis-cli -h $REDIS_HOST -p $REDIS_PORT ping 2>&1 | grep -q PONG; then
            echo "✅ Redis PING successful (no authentication)"
        else
            echo "❌ Redis PING failed"
            exit 1
        fi
    fi
else
    echo "⚠️  redis-cli not available, skipping protocol test"
    echo "   Install redis-tools to run this test: apt-get install redis-tools"
fi

echo ""
echo "======================================"
echo "✅ All available tests passed!"
echo ""
echo "💡 If your app still cannot connect:"
echo "1. Check that Redis bind address is 0.0.0.0 (not 127.0.0.1)"
echo "2. Verify password in REDIS_PASSWORD matches Redis config"
echo "3. Check Redis logs for authentication failures"
echo "4. Ensure firewall allows connections from Captain's IP"
echo ""

