#!/usr/bin/env bash

# Generate Kubernetes secrets securely

set -e

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

echo "Generating Kubernetes secrets..."

# Generate Blockscout secret key base
BLOCKSCOUT_SECRET_KEY_BASE=$(openssl rand -hex 32)
echo "Generated Blockscout secret_key_base"

# Generate PostgreSQL password
POSTGRES_PASSWORD=$(openssl rand -base64 32)
echo "Generated PostgreSQL password"

# Create secrets
kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f -

kubectl create secret generic blockscout-secrets \
  --namespace="$NAMESPACE" \
  --from-literal=secret_key_base="$BLOCKSCOUT_SECRET_KEY_BASE" \
  --dry-run=client -o yaml | kubectl apply -f -

kubectl create secret generic blockscout-db-secrets \
  --namespace="$NAMESPACE" \
  --from-literal=postgres_password="$POSTGRES_PASSWORD" \
  --dry-run=client -o yaml | kubectl apply -f -

# Generate RPC gateway SSL certificate (self-signed for now)
# In production, use proper certificates from a CA
echo "Generating SSL certificate for RPC gateway..."
mkdir -p "$PROJECT_ROOT/keys/ssl"
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout "$PROJECT_ROOT/keys/ssl/tls.key" \
  -out "$PROJECT_ROOT/keys/ssl/tls.crt" \
  -subj "/CN=rpc.defi-oracle-meta-mainnet.org/O=DeFi Oracle Meta Mainnet"

kubectl create secret tls rpc-gateway-ssl \
  --namespace="$NAMESPACE" \
  --cert="$PROJECT_ROOT/keys/ssl/tls.crt" \
  --key="$PROJECT_ROOT/keys/ssl/tls.key" \
  --dry-run=client -o yaml | kubectl apply -f -

echo "✓ Secrets generated and applied to namespace: $NAMESPACE"
echo "Note: In production, use Azure Key Vault or proper certificate management"
echo "for SSL certificates and other secrets."

