Files
vm-cc/20-collectors/collect_backup_restore_drill.sh
2025-12-27 02:14:14 +00:00

86 lines
2.1 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
OUT_DIR="${1:?usage: collect_backup_restore_drill.sh <out_dir>}"
mkdir -p "$OUT_DIR"
DEFAULT_GLOB="*restore*drill*.json"
DEFAULT_ROOTS=(
"../vm-ops/60-backups"
"../vm-skills"
)
matches=()
if [[ -n "${VMCC_RESTORE_DRILL_GLOB:-}" ]]; then
if [[ -f "$VMCC_RESTORE_DRILL_GLOB" ]]; then
matches+=("$VMCC_RESTORE_DRILL_GLOB")
elif [[ -d "$VMCC_RESTORE_DRILL_GLOB" ]]; then
while IFS= read -r -d '' file; do
matches+=("$file")
done < <(find "$VMCC_RESTORE_DRILL_GLOB" -type f -name "$DEFAULT_GLOB" -print0 2>/dev/null)
else
while IFS= read -r file; do
matches+=("$file")
done < <(compgen -G "$VMCC_RESTORE_DRILL_GLOB" || true)
fi
fi
if [[ ${#matches[@]} -eq 0 ]]; then
for root in "${DEFAULT_ROOTS[@]}"; do
if [[ -d "$root" ]]; then
while IFS= read -r -d '' file; do
matches+=("$file")
done < <(find "$root" -type f -name "$DEFAULT_GLOB" -print0 2>/dev/null)
fi
done
fi
file_mtime_epoch() {
local file="$1"
if stat -c %Y "$file" >/dev/null 2>&1; then
stat -c %Y "$file"
else
stat -f %m "$file"
fi
}
file_mtime_iso() {
local file="$1"
local mtime
mtime="$(file_mtime_epoch "$file")"
# BSD/macOS: date -r <epoch>
if date -u -r "$mtime" "+%Y-%m-%dT%H:%M:%SZ" >/dev/null 2>&1; then
date -u -r "$mtime" "+%Y-%m-%dT%H:%M:%SZ"
# GNU: date -d "@<epoch>"
elif date -u -d "@${mtime}" "+%Y-%m-%dT%H:%M:%SZ" >/dev/null 2>&1; then
date -u -d "@${mtime}" "+%Y-%m-%dT%H:%M:%SZ"
else
date -u "+%Y-%m-%dT%H:%M:%SZ"
fi
}
LATEST=""
LATEST_TS=0
for file in "${matches[@]}"; do
if [[ -f "$file" ]]; then
ts="$(file_mtime_epoch "$file")"
if [[ "$ts" -gt "$LATEST_TS" || ( "$ts" -eq "$LATEST_TS" && ( -z "$LATEST" || "$file" > "$LATEST" ) ) ]]; then
LATEST_TS="$ts"
LATEST="$file"
fi
fi
done
if [[ -n "$LATEST" ]]; then
TS="$(file_mtime_iso "$LATEST")"
jq -n \
--arg path "$LATEST" \
--arg ts "$TS" \
'{collected:true, path:$path, observed_at:$ts}' \
> "$OUT_DIR/backup_restore_drill.json"
else
jq -n '{collected:false, reason:"no restore drill artifacts found"}' \
> "$OUT_DIR/backup_restore_drill.json"
fi