#!/usr/bin/env bash

# Key rotation script for validator and oracle keys
# This script rotates keys in Azure Key Vault and updates Kubernetes secrets

set -e

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

# Configuration
KEY_VAULT_NAME="${KEY_VAULT_NAME:-defi-oracle-kv}"
NAMESPACE="${NAMESPACE:-besu-network}"
KEY_TYPE="${1:-validator}"  # validator or oracle
NUM_KEYS="${2:-4}"


log_success "Starting key rotation for $KEY_TYPE keys"

# Check if Azure CLI is installed
if ! command -v az &> /dev/null; then
    log_error "Error: Azure CLI not found. Please install Azure CLI."
    exit 1
fi

# Check if logged in to Azure
if ! az account show &> /dev/null; then
    log_error "Error: Not logged in to Azure. Please run 'az login'."
    exit 1
fi

# Generate new keys
log_warn "Generating new keys..."
for i in $(seq 1 $NUM_KEYS); do
    # Generate new private key
    NEW_KEY=$(openssl rand -hex 32)
    
    # Store in Key Vault
    KEY_NAME="${KEY_TYPE}-key-${i}"
    az keyvault secret set \
        --vault-name "$KEY_VAULT_NAME" \
        --name "$KEY_NAME" \
        --value "$NEW_KEY" \
        --content-type "text/plain" \
        --tags "type=$KEY_TYPE" "index=$i" "rotated=$(date +%Y-%m-%d)"
    
    if [ $? -eq 0 ]; then
        log_success "✓ Key stored in Key Vault: $KEY_NAME"
    else
        log_error "✗ Failed to store key in Key Vault: $KEY_NAME"
        exit 1
    fi
done

# Update Kubernetes secrets
log_warn "Updating Kubernetes secrets..."
SECRET_NAME="besu-${KEY_TYPE}-keys"

# Create secret from Key Vault
kubectl create secret generic "$SECRET_NAME" \
    --from-literal=key-1=$(az keyvault secret show --vault-name "$KEY_VAULT_NAME" --name "${KEY_TYPE}-key-1" --query value -o tsv) \
    --from-literal=key-2=$(az keyvault secret show --vault-name "$KEY_VAULT_NAME" --name "${KEY_TYPE}-key-2" --query value -o tsv) \
    --from-literal=key-3=$(az keyvault secret show --vault-name "$KEY_VAULT_NAME" --name "${KEY_TYPE}-key-3" --query value -o tsv) \
    --from-literal=key-4=$(az keyvault secret show --vault-name "$KEY_VAULT_NAME" --name "${KEY_TYPE}-key-4" --query value -o tsv) \
    -n "$NAMESPACE" \
    --dry-run=client -o yaml | kubectl apply -f -

if [ $? -eq 0 ]; then
    log_success "✓ Kubernetes secret updated: $SECRET_NAME"
else
    log_error "✗ Failed to update Kubernetes secret"
    exit 1
fi

# Restart pods to use new keys
log_warn "Restarting pods to use new keys..."
if [ "$KEY_TYPE" == "validator" ]; then
    kubectl rollout restart statefulset/besu-validator -n "$NAMESPACE"
    log_success "✓ Validator pods restarted"
elif [ "$KEY_TYPE" == "oracle" ]; then
    kubectl rollout restart deployment/oracle-publisher -n "$NAMESPACE"
    log_success "✓ Oracle publisher pods restarted"
fi

# Wait for pods to be ready
log_warn "Waiting for pods to be ready..."
if [ "$KEY_TYPE" == "validator" ]; then
    kubectl wait --for=condition=ready pod -l component=validator -n "$NAMESPACE" --timeout=300s
elif [ "$KEY_TYPE" == "oracle" ]; then
    kubectl wait --for=condition=ready pod -l app=oracle-publisher -n "$NAMESPACE" --timeout=300s
fi

# Verify keys are working
log_warn "Verifying keys are working..."
# Add verification logic here
# For validators: Check if blocks are being produced
# For oracle: Check if oracle updates are working

log_success "Key rotation completed successfully"

# Archive old keys (optional)
log_warn "Archiving old keys..."
# Move old keys to archive in Key Vault
# az keyvault secret set --vault-name "$KEY_VAULT_NAME" --name "${KEY_TYPE}-key-1-archived-$(date +%Y%m%d)" --value "<old-key>"

log_success "Key rotation process completed"

