#!/bin/bash

set -euo pipefail

# Default version if not provided
DEFAULT_VERSION="2.8.2"
VERSION=${1:-$DEFAULT_VERSION}

# Base directory paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DASHBOARDS_DIR="$SCRIPT_DIR/$VERSION/dashboards"
OUTPUT_DIR="$SCRIPT_DIR"

# Validate version directory exists
if [[ ! -d "$DASHBOARDS_DIR" ]]; then
    echo "Error: Version directory '$DASHBOARDS_DIR' does not exist"
    echo "Available versions:"
    ls -1 "$SCRIPT_DIR" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' || echo "  No version directories found"
    exit 1
fi

# Validate dashboards exist
if [[ ! -d "$DASHBOARDS_DIR" ]] || [[ -z "$(ls -A "$DASHBOARDS_DIR"/*.json 2>/dev/null)" ]]; then
    echo "Error: No JSON dashboard files found in '$DASHBOARDS_DIR'"
    exit 1
fi

echo "Generating ConfigMaps from dashboard files in version $VERSION..."

# Process each JSON file in the dashboards directory
for json_file in "$DASHBOARDS_DIR"/*.json; do
    if [[ ! -f "$json_file" ]]; then
        continue
    fi
    
    # Extract filename without extension
    filename=$(basename "$json_file" .json)
    
    # Generate ConfigMap name by replacing underscores with hyphens
    configmap_name="${filename//_/-}-dashboard"
    
    # Output YAML file path
    yaml_file="$OUTPUT_DIR/$filename.yaml"
    
    echo "Processing: $json_file -> $yaml_file"
    
    # Generate ConfigMap YAML
    cat > "$yaml_file" << EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: $configmap_name
  namespace: freeleaps-monitoring-system
  labels:
    grafana_dashboard: "1"
data:
  $filename.json: |-
EOF
    
    # Add JSON content with proper indentation
    sed 's/^/    /' "$json_file" >> "$yaml_file"
    
    echo "Generated: $yaml_file"
done

echo "ConfigMap generation completed for version $VERSION"
echo "Generated files are located in: $OUTPUT_DIR"