#!/usr/bin/env bash

# Validate RBAC Configuration
# This script validates that RBAC is correctly configured

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 RBAC Configuration..."

# Check if Service Accounts exist
log_warn "Checking Service Accounts..."
SERVICE_ACCOUNTS=(
    "besu-validator"
    "besu-sentry"
    "besu-rpc"
    "oracle-publisher"
    "rpc-gateway"
)

for sa in "${SERVICE_ACCOUNTS[@]}"; do
    if kubectl get serviceaccount "$sa" -n "$NAMESPACE" &>/dev/null; then
        log_success "✓ Service Account $sa exists"
    else
        log_warn "⚠ Service Account $sa not found, applying..."
        kubectl apply -f "$PROJECT_ROOT/k8s/rbac/service-accounts.yaml"
        break
    fi
done

# Check if Roles exist
log_warn "Checking Roles..."
if kubectl get role keyvault-reader -n "$NAMESPACE" &>/dev/null; then
    log_success "✓ Role keyvault-reader exists"
else
    log_warn "⚠ Role keyvault-reader not found, applying..."
    kubectl apply -f "$PROJECT_ROOT/k8s/rbac/service-accounts.yaml"
fi

# Check if RoleBindings exist
log_warn "Checking RoleBindings..."
ROLE_BINDINGS=(
    "validator-keyvault-reader"
    "oracle-keyvault-reader"
)

for rb in "${ROLE_BINDINGS[@]}"; do
    if kubectl get rolebinding "$rb" -n "$NAMESPACE" &>/dev/null; then
        log_success "✓ RoleBinding $rb exists"
    else
        log_warn "⚠ RoleBinding $rb not found"
    fi
done

# Validate Service Account permissions
log_warn "Validating Service Account permissions..."

# Test if validator service account can read secrets
VALIDATOR_SA="besu-validator"
if kubectl auth can-i get secrets --as=system:serviceaccount:$NAMESPACE:$VALIDATOR_SA -n "$NAMESPACE" 2>/dev/null | grep -q "yes"; then
    log_success "✓ Service Account $VALIDATOR_SA can read secrets"
else
    log_warn "⚠ Service Account $VALIDATOR_SA cannot read secrets (may be expected)"
fi

# Check if pods are using correct service accounts
log_warn "Checking pod service accounts..."
VALIDATOR_PODS=$(kubectl get pods -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[*].metadata.name}' 2>/dev/null || echo "")

if [ -n "$VALIDATOR_PODS" ]; then
    for pod in $VALIDATOR_PODS; do
        SA=$(kubectl get pod "$pod" -n "$NAMESPACE" -o jsonpath='{.spec.serviceAccountName}' 2>/dev/null || echo "")
        if [ "$SA" == "$VALIDATOR_SA" ]; then
            log_success "✓ Pod $pod is using correct service account"
        else
            log_warn "⚠ Pod $pod is using service account: $SA"
        fi
    done
else
    log_warn "⚠ No validator pods found for validation"
fi

log_success "RBAC validation completed"

