#!/bin/bash

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# Script to build src/domains.rs from config/Domains.json
# Generates a Rust module with static domain constants

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
JSON_FILE="$SCRIPT_DIR/../config/Domains.json"
RS_FILE="$SCRIPT_DIR/../src/domains.rs"

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

if [[ ! -f "$JSON_FILE" ]]; then
    echo "Error: Domains.json not found in $SCRIPT_DIR/../config/"
    exit 1
fi

# Generate Rust file
cat > "$RS_FILE" << 'EOF'
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Well-known Azure service domains for internal use.
//!
//! This file is auto-generated from config/Domains.json.
//! Do not edit this file manually. Run scripts/build-domains-rust.sh to regenerate.

EOF

# Generate Azure Key Vault domains
{
    echo "/// Azure Key Vault service domains across all public Azure environments."
    echo "pub const AZURE_KEY_VAULT_DOMAINS: &[&str] = &["
    jq -r '.azureKeyVault.domains[] | "    \"" + . + "\","' "$JSON_FILE"
    echo "];"
    echo ""
} >> "$RS_FILE"

# Generate Azure Storage domains
{
    echo "/// Azure Storage service domains across all public Azure environments."
    echo "pub const AZURE_STORAGE_DOMAINS: &[&str] = &["
    jq -r '.azureStorage.domains[] | "    \"" + . + "\","' "$JSON_FILE"
    echo "];"
} >> "$RS_FILE"

echo "Successfully generated $RS_FILE"
