#!/bin/bash

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

# Script to build src/ip_address_ranges.rs from config/IPAddressRanges.json
# Generates a Rust module with static constants

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
JSON_FILE="$SCRIPT_DIR/../config/IPAddressRanges.json"
RS_FILE="$SCRIPT_DIR/../src/ip_address_ranges.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: IPAddressRanges.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.

//! Static IP address ranges for AntiSSRF protection.
//!
//! This file is auto-generated from config/IPAddressRanges.json.
//! Do not edit this file manually. Run scripts/build-ip-ranges-rust.sh to regenerate.

EOF

# Generate individual constants
jq -r '
  to_entries
  | map(select(.key != "_sources" and .value.standaloneVariable == true))
  | .[]
  | "pub const " + (.key | ascii_upcase) + ": &[&str] = &[\n" + (.value.cidr | map("    \"" + . + "\"") | join(",\n")) + "\n];\n"
' "$JSON_FILE" >> "$RS_FILE"

# Add recommendedLatest
{
    echo ""
    echo "/// Recommended latest always points to the current version."
    echo "pub const RECOMMENDED_LATEST: &[&str] = RECOMMENDEDV1;"
} >> "$RS_FILE"

echo "Successfully generated $RS_FILE"
