#!/bin/bash

# Fix OTEL endpoint configuration in all service manifests
# This script replaces hardcoded OTEL_EXPORTER_OTLP_ENDPOINT values
# with references to the central bakery-config ConfigMap

set -e

GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}Fixing OTEL endpoint configuration in all services...${NC}"
echo ""

# Find all service YAML files
SERVICE_FILES=$(find infrastructure/kubernetes/base/components -name "*-service.yaml")

for file in $SERVICE_FILES; do
    # Check if file contains hardcoded OTEL_EXPORTER_OTLP_ENDPOINT
    if grep -q "name: OTEL_EXPORTER_OTLP_ENDPOINT" "$file"; then
        # Check if it's already using configMapKeyRef
        if grep -A 3 "name: OTEL_EXPORTER_OTLP_ENDPOINT" "$file" | grep -q "configMapKeyRef"; then
            echo -e "${GREEN}✓ $file already using ConfigMap${NC}"
        else
            echo -e "${BLUE}→ Fixing $file${NC}"

            # Create a temporary file
            tmp_file=$(mktemp)

            # Process the file
            awk '
            /name: OTEL_EXPORTER_OTLP_ENDPOINT/ {
                print $0
                # Read and skip the next line (value line)
                getline
                # Output the configMapKeyRef instead
                print "          valueFrom:"
                print "            configMapKeyRef:"
                print "              name: bakery-config"
                print "              key: OTEL_EXPORTER_OTLP_ENDPOINT"
                next
            }
            { print }
            ' "$file" > "$tmp_file"

            # Replace original file
            mv "$tmp_file" "$file"
            echo -e "${GREEN}  ✓ Fixed${NC}"
        fi
    fi
done

echo ""
echo -e "${GREEN}✓ All service files processed!${NC}"
echo ""
echo "Next steps:"
echo "1. Review changes: git diff infrastructure/kubernetes/base/components"
echo "2. Apply changes: kubectl apply -k infrastructure/environments/dev/k8s-manifests"
echo "3. Restart services: kubectl rollout restart deployment -n bakery-ia --all"
