#!/usr/bin/env bash

# Validate Network Policies
# This script validates that Network Policies are correctly applied and working

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
NAMESPACE="${NAMESPACE:-besu-network}"


log_success "Validating Network Policies..."

# Check if Network Policies are applied
log_warn "Checking Network Policies..."
NETWORK_POLICIES=$(kubectl get networkpolicies -n "$NAMESPACE" -o name 2>/dev/null || echo "")

if [ -z "$NETWORK_POLICIES" ]; then
    log_error "✗ No Network Policies found in namespace $NAMESPACE"
    log_warn "Applying Network Policies..."
    kubectl apply -f "$PROJECT_ROOT/k8s/network-policies/default-deny.yaml"
else
    log_success "✓ Network Policies found:"
    echo "$NETWORK_POLICIES"
fi

# Validate specific policies
log_warn "Validating specific policies..."

# Check default-deny policy
if kubectl get networkpolicy default-deny-all -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ default-deny-all policy exists"
else
    log_error "✗ default-deny-all policy not found"
    exit 1
fi

# Check validator policy
if kubectl get networkpolicy allow-validator-internal -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ allow-validator-internal policy exists"
else
    log_error "✗ allow-validator-internal policy not found"
    exit 1
fi

# Check sentry policy
if kubectl get networkpolicy allow-sentry-p2p -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ allow-sentry-p2p policy exists"
else
    log_error "✗ allow-sentry-p2p policy not found"
    exit 1
fi

# Check RPC policy
if kubectl get networkpolicy allow-rpc-http -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ allow-rpc-http policy exists"
else
    log_error "✗ allow-rpc-http policy not found"
    exit 1
fi

# Test pod-to-pod communication (if pods are running)
log_warn "Testing pod-to-pod communication..."

VALIDATOR_PODS=$(kubectl get pods -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || echo "")
RPC_PODS=$(kubectl get pods -n "$NAMESPACE" -l component=rpc -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || echo "")

if [ -n "$VALIDATOR_PODS" ] && [ -n "$RPC_PODS" ]; then
    log_warn "Testing connectivity from validator to RPC (should be blocked)..."
    # This should be blocked by Network Policies
    if kubectl exec -n "$NAMESPACE" "$VALIDATOR_PODS" -- nc -zv besu-rpc-0.besu-rpc.besu-network.svc.cluster.local 8545 2>&1 | grep -q "Connection refused\|timeout"; then
        log_success "✓ Network Policies are working (connection blocked as expected)"
    else
        log_warn "⚠ Connection test inconclusive (pods may not be ready)"
    fi
else
    log_warn "⚠ Pods not ready for connectivity testing"
fi

log_success "Network Policies validation completed"

