#!/usr/bin/env bash
# RPC failover and redundancy management
# Usage: ./rpc-failover.sh [primary|backup|test]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

source "$SOURCE_PROJECT/.env" 2>/dev/null || true

# RPC endpoints (add backup endpoints here)
PRIMARY_RPC="${RPC_URL_138:-http://192.168.11.250:8545}"
BACKUP_RPC="${RPC_URL_138_BACKUP:-http://192.168.11.250:8545}"  # Add backup endpoint
HTTPS_RPC="https://rpc-core.d-bis.org"

ACTION="${1:-test}"

# Test RPC endpoint
test_rpc() {
    local rpc_url="$1"
    if cast block-number --rpc-url "$rpc_url" >/dev/null 2>&1; then
        echo "✅ $rpc_url: Accessible"
        return 0
    else
        echo "❌ $rpc_url: Not accessible"
        return 1
    fi
}

# Get working RPC endpoint
get_working_rpc() {
    if test_rpc "$PRIMARY_RPC"; then
        echo "$PRIMARY_RPC"
    elif test_rpc "$HTTPS_RPC"; then
        echo "$HTTPS_RPC"
    elif test_rpc "$BACKUP_RPC"; then
        echo "$BACKUP_RPC"
    else
        echo ""
    fi
}

# Test all endpoints
test_all() {
    echo "=== Testing RPC Endpoints ==="
    echo ""
    test_rpc "$PRIMARY_RPC"
    test_rpc "$HTTPS_RPC"
    test_rpc "$BACKUP_RPC"
    echo ""
    
    WORKING_RPC=$(get_working_rpc)
    if [ -n "$WORKING_RPC" ]; then
        echo "✅ Working endpoint: $WORKING_RPC"
    else
        echo "❌ No working endpoints found"
        return 1
    fi
}

# Use primary endpoint
use_primary() {
    export RPC_URL_138="$PRIMARY_RPC"
    echo "Using primary RPC: $PRIMARY_RPC"
}

# Use backup endpoint
use_backup() {
    export RPC_URL_138="$BACKUP_RPC"
    echo "Using backup RPC: $BACKUP_RPC"
}

# Auto-failover
auto_failover() {
    WORKING_RPC=$(get_working_rpc)
    if [ -n "$WORKING_RPC" ]; then
        export RPC_URL_138="$WORKING_RPC"
        echo "Auto-selected RPC: $WORKING_RPC"
        return 0
    else
        echo "ERROR: No working RPC endpoints"
        return 1
    fi
}

case "$ACTION" in
    test) test_all ;;
    primary) use_primary ;;
    backup) use_backup ;;
    auto) auto_failover ;;
    *)
        echo "Usage: $0 [test|primary|backup|auto]"
        exit 1
        ;;
esac

