#!/bin/bash
# Upload Genesis File to Azure Key Vault
# This script uploads the genesis file to Azure Key Vault for secure distribution

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE1_DIR="$SCRIPT_DIR/../"
GENESIS_FILE="$PHASE1_DIR/config/genesis-138.json"

if [ ! -f "$GENESIS_FILE" ]; then
    echo "Error: Genesis file not found: $GENESIS_FILE"
    exit 1
fi

echo "=========================================="
echo "Upload Genesis File to Azure Key Vault"
echo "=========================================="
echo ""

# Get Key Vault from Terraform output
cd "$PHASE1_DIR"
KEY_VAULT=$(terraform output -json 2>/dev/null | jq -r '.key_vault_name.value // empty' || echo "")

if [ -z "$KEY_VAULT" ]; then
    echo "Error: Could not retrieve Key Vault from Terraform output"
    echo "Please ensure Terraform has been applied and outputs are available"
    exit 1
fi

echo "Key Vault: $KEY_VAULT"
echo "Genesis File: $GENESIS_FILE"
echo ""

# Upload as secret
echo "Uploading genesis file as secret..."
az keyvault secret set \
    --vault-name "$KEY_VAULT" \
    --name "genesis-138" \
    --file "$GENESIS_FILE" \
    --output none

echo ""
echo "=========================================="
echo "Upload Complete!"
echo "=========================================="
echo "Key Vault: $KEY_VAULT"
echo "Secret Name: genesis-138"
echo ""
echo "To download on a VM (with Managed Identity):"
echo "  az keyvault secret show --vault-name $KEY_VAULT --name genesis-138 --query value -o tsv > /opt/besu/config/genesis.json"
echo ""

