#!/bin/bash

# Set the base URL for the metrics export
BASE_URL="http://127.0.0.1:8481/select/39523:22/prometheus/api/v1/export/native"

# Create output directory if it doesn't exist
OUTPUT_DIR="metrics_exports_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUTPUT_DIR"

# Start and end timestamps (August 26 09:00 to August 28 20:00 2025)
# Using UTC time to avoid timezone issues
START_TIMESTAMP=$(date -j -f "%Y-%m-%d %H:%M:%S" "2025-08-23 09:00:00" +%s)
END_TIMESTAMP=$(date -j -f "%Y-%m-%d %H:%M:%S" "2025-09-01 20:00:00" +%s)

# Current timestamp for iteration
current_ts=$START_TIMESTAMP

# Loop through each hour
while [ $current_ts -lt $END_TIMESTAMP ]; do
    # Calculate end of current hour (3600 seconds = 1 hour)
    next_ts=$((current_ts + 3600))
    
    # If next_ts exceeds END_TIMESTAMP, use END_TIMESTAMP
    if [ $next_ts -gt $END_TIMESTAMP ]; then
        next_ts=$END_TIMESTAMP
    fi
    
    # Format the timestamps for the filename (YYYYMMDD_HHMM format)
    start_str=$(date -r $current_ts +"%Y%m%d_%H%M")
    end_str=$(date -r $next_ts +"%Y%m%d_%H%M")
    
    # Generate the output filename
    output_file="${OUTPUT_DIR}/metrics_${start_str}_${end_str}.prom"
    
    echo "Exporting metrics from $(date -r $current_ts) to $(date -r $next_ts) -> $output_file"
    
    # Make the curl request
    curl -s "$BASE_URL" \
        -d "start=${current_ts}000&end=${next_ts}000&match[]={__name__!=\"\"}" \
        -o "$output_file"
    
    # Check if file is empty and remove if it is
    if [ ! -s "$output_file" ]; then
        echo "  Warning: No data for this time range, removing empty file"
        rm -f "$output_file"
    fi
    
    # Move to next hour
    current_ts=$next_ts
done

echo "Export completed. Files are saved in: $OUTPUT_DIR"
# Count the number of files created
file_count=$(ls -1 "$OUTPUT_DIR"/*.prom 2>/dev/null | wc -l)
echo "Total files created: $file_count"
