#!/usr/bin/env bash

set -e

# Generate validator keys for QBFT
# This script generates validator keypairs for Besu QBFT consensus

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

NUM_VALIDATORS=${1:-4}
PASSWORD_FILE="${2:-$PROJECT_ROOT/keys/.password}"

echo "Generating $NUM_VALIDATORS validator keys..."

# Create password file if it doesn't exist
if [ ! -f "$PASSWORD_FILE" ]; then
    mkdir -p "$(dirname "$PASSWORD_FILE")"
    openssl rand -base64 32 > "$PASSWORD_FILE"
    chmod 600 "$PASSWORD_FILE"
    echo "Created password file: $PASSWORD_FILE"
fi

# Generate keys
for i in $(seq 1 $NUM_VALIDATORS); do
    VALIDATOR_DIR="$KEYS_DIR/validator-$i"
    mkdir -p "$VALIDATOR_DIR"
    
    # Generate private key
    PRIVATE_KEY=$(openssl rand -hex 32)
    echo "$PRIVATE_KEY" > "$VALIDATOR_DIR/key.priv"
    chmod 600 "$VALIDATOR_DIR/key.priv"
    
    # Create keystore using Besu if available
    if command -v besu &> /dev/null; then
        echo "$(cat "$PASSWORD_FILE")" | besu --data-path="$VALIDATOR_DIR" \
            account import --private-key="$VALIDATOR_DIR/key.priv" \
            --password-file=<(echo "$(cat "$PASSWORD_FILE")") 2>/dev/null || true
    fi
    
    echo "Generated validator $i key: $VALIDATOR_DIR/key.priv"
done

echo "Validator keys generated in: $KEYS_DIR"
echo "Password file: $PASSWORD_FILE"
echo "IMPORTANT: Store keys securely. For production, use Azure Key Vault or HSM."
