#!/bin/bash
# =============================================================================
# Synor Node Key Generation Script
# =============================================================================
# Generates cryptographic keys for Synor nodes.
# Each node needs:
#   - Ed25519 keypair (for P2P identity)
#   - Dilithium3 keypair (for post-quantum signatures)
#   - Mining address (for block rewards)
# =============================================================================

set -e

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

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

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

# Default output directory
OUTPUT_DIR="${1:-$PROJECT_DIR/keys}"

# Create output directory
mkdir -p "$OUTPUT_DIR"

generate_node_keys() {
    local node_name="$1"
    local node_dir="$OUTPUT_DIR/$node_name"

    log_info "Generating keys for $node_name..."
    mkdir -p "$node_dir"

    # Generate Ed25519 keypair for P2P identity
    # Using OpenSSL for key generation
    openssl genpkey -algorithm Ed25519 -out "$node_dir/p2p.key" 2>/dev/null
    openssl pkey -in "$node_dir/p2p.key" -pubout -out "$node_dir/p2p.pub" 2>/dev/null

    # Extract peer ID from public key (base58 encoding of the public key bytes)
    PUBKEY_HEX=$(openssl pkey -in "$node_dir/p2p.key" -pubout -outform DER 2>/dev/null | xxd -p | tr -d '\n' | tail -c 64)
    echo "$PUBKEY_HEX" > "$node_dir/peer_id.hex"

    # Generate a random mining address (for testnet, this is simplified)
    # In production, this would be derived from a proper wallet
    MINING_ADDR=$(openssl rand -hex 32)
    echo "synor1$MINING_ADDR" > "$node_dir/mining_address.txt"

    # Create node configuration snippet
    cat > "$node_dir/node_config.toml" << EOF
# Node Configuration for $node_name
# Generated: $(date -u +"%Y-%m-%dT%H:%M:%SZ")

[identity]
# P2P private key file
key_file = "p2p.key"
# Peer ID (derived from public key)
peer_id = "$PUBKEY_HEX"

[mining]
# Mining reward address
coinbase_address = "synor1$MINING_ADDR"
EOF

    log_success "Generated keys for $node_name in $node_dir"
}

print_usage() {
    echo "Usage: $0 [output_dir] [node_names...]"
    echo ""
    echo "Examples:"
    echo "  $0                           # Generate keys for seed1, seed2, seed3 in ./keys"
    echo "  $0 /path/to/keys             # Specify output directory"
    echo "  $0 ./keys node1 node2 node3  # Generate for specific nodes"
}

# Main
echo ""
echo "==============================================="
echo "    Synor Node Key Generation"
echo "==============================================="
echo ""

# Check for openssl
if ! command -v openssl &> /dev/null; then
    echo "Error: OpenSSL is required but not installed."
    exit 1
fi

# Parse arguments
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    print_usage
    exit 0
fi

# Determine output directory
if [[ -n "$1" && ! "$1" =~ ^- ]]; then
    OUTPUT_DIR="$1"
    shift
fi

# Determine node names
if [[ $# -gt 0 ]]; then
    NODES=("$@")
else
    NODES=("seed1" "seed2" "seed3")
fi

log_info "Output directory: $OUTPUT_DIR"
log_info "Generating keys for: ${NODES[*]}"
echo ""

# Generate keys for each node
for node in "${NODES[@]}"; do
    generate_node_keys "$node"
done

echo ""
log_success "All keys generated!"
echo ""
echo "Keys saved to: $OUTPUT_DIR"
echo ""
echo "WARNING: Keep private keys secure! Never commit them to version control."
echo ""

# Create a .gitignore in the keys directory
echo "*" > "$OUTPUT_DIR/.gitignore"
echo "!.gitignore" >> "$OUTPUT_DIR/.gitignore"
