#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
BACKUP_ROOT="${1:-$ROOT_DIR/backups}"
KEEP_COUNT="${2:-14}"

if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  cat <<'USAGE'
Usage:
  scripts/ops/prune-backups.sh [backup-root] [keep-count]

Examples:
  scripts/ops/prune-backups.sh
  scripts/ops/prune-backups.sh /var/backups/productier 30
USAGE
  exit 0
fi

if ! [[ "$KEEP_COUNT" =~ ^[0-9]+$ ]] || [[ "$KEEP_COUNT" -lt 1 ]]; then
  echo "[error] keep-count must be a positive integer" >&2
  exit 1
fi

if [[ ! -d "$BACKUP_ROOT" ]]; then
  echo "[info] backup root does not exist; nothing to prune"
  exit 0
fi

mapfile -t backup_dirs < <(
  find "$BACKUP_ROOT" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' \
    | grep -E '^[0-9]{8}T[0-9]{6}Z$' \
    | sort -r
)

if [[ "${#backup_dirs[@]}" -le "$KEEP_COUNT" ]]; then
  echo "[info] no pruning needed (${#backup_dirs[@]} backup(s), keep=$KEEP_COUNT)"
  exit 0
fi

for backup_name in "${backup_dirs[@]:$KEEP_COUNT}"; do
  target="$BACKUP_ROOT/$backup_name"
  echo "[step] removing old backup: $target"
  rm -rf "$target"
done

echo "[ok] pruned backups, kept latest $KEEP_COUNT"
