#!/usr/bin/env bash

set -e

# Generate oracle keys for EthSigner
# Oracle keys are used to sign transactions for oracle updates

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/oracle"

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

echo "Generating $NUM_ORACLES oracle 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_ORACLES); do
    ORACLE_DIR="$KEYS_DIR/oracle-$i"
    mkdir -p "$ORACLE_DIR"
    
    # Generate private key
    PRIVATE_KEY=$(openssl rand -hex 32)
    echo "$PRIVATE_KEY" > "$ORACLE_DIR/key.priv"
    chmod 600 "$ORACLE_DIR/key.priv"
    
    # Create keystore for EthSigner
    if command -v ethsigner &> /dev/null; then
        ethsigner --data-path="$ORACLE_DIR" \
            account import --private-key-file="$ORACLE_DIR/key.priv" \
            --password-file="$PASSWORD_FILE" 2>/dev/null || true
    fi
    
    echo "Generated oracle $i key: $ORACLE_DIR/key.priv"
done

echo "Oracle keys generated in: $KEYS_DIR"
echo "Password file: $PASSWORD_FILE"
echo "IMPORTANT: Store keys securely in Azure Key Vault for production."

