#!/usr/bin/env bash
#
# Copyright 2026 The Cockroach Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
# ######################################################################
#
# Extract metrics snapshots taken by the periodic metrics snapshotter
# within a time range into a tar.gz archive for debugging/analysis.
#
# The exported archive can be imported into a local Prometheus instance
# using the companion import-metrics-snapshots.sh script.
#
# Usage:
#   ./export-metrics-snapshots.sh <snapshot-dir> [start-time] [end-time] [output-file]
#
# If no times are specified, all snapshots are exported. If only a start
# time is specified, all snapshots from that time onward are exported.
#
# Times are in UTC and should be in format: YYYYMMDDTHHMMSS (e.g., 20260115T120000).
# This matches the timestamp format used in snapshot filenames.
#
# Examples:
#   ./export-metrics-snapshots.sh ./replicator-data/metrics-snapshots
#   ./export-metrics-snapshots.sh ./replicator-data/metrics-snapshots 20260115T120000
#   ./export-metrics-snapshots.sh ./replicator-data/metrics-snapshots 20260115T120000 20260115T140000

set -euo pipefail

if [[ $# -lt 1 || $# -gt 4 ]]; then
    echo "Usage: $0 <snapshot-dir> [start-time] [end-time] [output-file]"
    echo ""
    echo "If no times are specified, all snapshots are exported."
    echo "If only a start time is specified, all snapshots from that time onward are exported."
    echo ""
    echo "Times are in UTC and should be in format: YYYYMMDDTHHMMSS (e.g., 20260115T120000)"
    echo ""
    echo "Examples:"
    echo "  $0 ./replicator-data/metrics-snapshots"
    echo "  $0 ./replicator-data/metrics-snapshots 20260115T120000"
    echo "  $0 ./replicator-data/metrics-snapshots 20260115T120000 20260115T140000"
    exit 1
fi

SNAPSHOT_DIR="$1"
START_TIME="${2:-}"
END_TIME="${3:-}"

# Default end time to now (UTC) when only start is specified.
if [[ -n "$START_TIME" && -z "$END_TIME" ]]; then
    END_TIME=$(date -u +%Y%m%dT%H%M%S)
fi

if [[ -n "$START_TIME" ]]; then
    OUTPUT_FILE="${4:-replicator-metrics-snapshots-${START_TIME}-to-${END_TIME}.tar.gz}"
else
    OUTPUT_FILE="${4:-replicator-metrics-snapshots-all.tar.gz}"
fi

if [[ ! -d "$SNAPSHOT_DIR" ]]; then
    echo "Error: Directory not found: $SNAPSHOT_DIR" >&2
    exit 1
fi

# Copy matching files to temp dir to avoid race with retention deleting files mid-archive
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

copied=0
for f in "$SNAPSHOT_DIR"/snapshot-*.txt "$SNAPSHOT_DIR"/snapshot-*.txt.gz; do
    # Skip if no files matched the glob (bash returns the literal pattern)
    [[ -e "$f" ]] || continue

    # Extract timestamp from filename: snapshot-20260115T120000.000Z.txt.gz -> 20260115T120000
    basename=$(basename "$f")
    ts=$(echo "$basename" | sed -n 's/^snapshot-\([0-9]\{8\}T[0-9]\{6\}\)\.[0-9]*Z\.txt.*$/\1/p')

    # Skip if timestamp couldn't be parsed from filename
    [[ -z "$ts" ]] && continue

    # String comparison works because format is lexicographically sortable
    if [[ -n "$START_TIME" && "$ts" < "$START_TIME" ]]; then
        continue
    fi
    if [[ -n "$END_TIME" && "$ts" > "$END_TIME" ]]; then
        continue
    fi

    # Copy may fail if retention deleted the file; ignore and continue
    if cp "$f" "$tmpdir/" 2>/dev/null; then
        ((copied++))
    fi
done

if [[ $copied -eq 0 ]]; then
    if [[ -z "$START_TIME" ]]; then
        echo "No snapshots found"
    else
        echo "No snapshots found in range $START_TIME to $END_TIME"
    fi
    exit 0
fi

echo "Found $copied snapshots"
echo "Creating: $OUTPUT_FILE"

# Archive from temp dir (safe - retention can't delete from here)
(cd "$tmpdir" && tar -c snapshot-*) | gzip -9 > "$OUTPUT_FILE"

echo "Done: $OUTPUT_FILE (contains $copied snapshots)"
echo "If applicable, please upload this file to Zendesk."
