#!/usr/bin/env bash set -euo pipefail [ -d "$BACKUP_DIR" ] || { echo "Not a directory: $BACKUP_DIR" >&2 exit 1 } ts_regex='^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$' shopt -s nullglob candidates=() for p in "$BACKUP_DIR"/*; do [[ -d "$p" ]] || continue name="${p##*/}" [[ "$name" =~ $ts_regex ]] && candidates+=("$name") done shopt -u nullglob if ((${#candidates[@]} == 0)); then echo "No matching timestamp directories found in $BACKUP_DIR" exit 0 fi mapfile -t sorted < <(printf '%s\n' "${candidates[@]}" | LC_ALL=C sort -r) newest="${sorted[0]}" newest_path="${BACKUP_DIR%/}/$newest" for name in "${sorted[@]:1}"; do rm -rf -- "${BACKUP_DIR%/}/$name" done date_part="${newest%%T*}" if date --version >/dev/null 2>&1; then weekname="$(date -d "$date_part" +%G-W%V)" else weekname="$(date -jf "%Y-%m-%d" "$date_part" +%G-W%V)" fi target="${BACKUP_DIR%/}/${weekname}" if [[ "$newest_path" == "$target" ]]; then echo "Newest directory already named '$target'. Done." exit 0 fi if [[ -e "$target" && "$target" != "$newest_path" ]]; then echo "Target '$target' already exists. Refusing to overwrite." >&2 exit 1 fi mv -- "$newest_path" "$target" echo "rolled $newest over to $target"