#!/bin/bash
# Secure Validator Key Permissions
# Run on Proxmox host after validator keys are deployed

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARNING]${NC} $1"; }

if ! command -v pct >/dev/null 2>&1; then
    echo "Error: pct command not found. This script must be run on Proxmox host."
    exit 1
fi

if [[ $EUID -ne 0 ]]; then
    echo "Error: This script must be run as root"
    exit 1
fi

# Secure keys in validator containers
for vmid in 1000 1001 1002 1003 1004; do
    if pct status "$vmid" 2>/dev/null | grep -q running; then
        log_info "Securing keys in container $vmid..."
        
        # Set file permissions to 600 for key files
        pct exec "$vmid" -- find /keys/validators -type f \( -name "*.pem" -o -name "*.priv" -o -name "key" \) -exec chmod 600 {} \; 2>/dev/null || true
        
        # Set directory permissions
        pct exec "$vmid" -- find /keys/validators -type d -exec chmod 700 {} \; 2>/dev/null || true
        
        # Set ownership to besu:besu
        pct exec "$vmid" -- chown -R besu:besu /keys/validators 2>/dev/null || true
        
        log_success "Container $vmid secured"
    else
        log_warn "Container $vmid is not running, skipping"
    fi
done

log_success "Validator key security check complete!"
