aboutsummaryrefslogtreecommitdiff
path: root/scripts/rollover/rollover.sh
blob: d6e3fab725bc1f2777d42e7ae526703f8830326a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/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"