summaryrefslogtreecommitdiff
path: root/removeOldBackups.in
blob: 67d0828492b1ea1bedcedab381f2e77ecb7c966e (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
55
56
57
58
59
60
61
62
63
64
65
66
#!/bin/bash

# removeOldBackups version #VERSION#

[ -r "#ETCDIR#/backup.conf" ] && \
  . "#ETCDIR#/backup.conf"

usage () {
  >&2 echo \
'Usage: removeOldBackups
Remove old backups keeping only one backup per month for all but the present year.

Options:
#HELPTEXT#  #'
  [ -n "$1" ] && exit $1
  exit 1
}

if [ $# -eq 1 ]
then
  if [ "$1" == "--help" ]
  then
    usage 0
  elif [ "$1" == "--version" ]
  then
    >&2 echo '#VERSION#'
    exit 0
  fi
  usage
elif [ $# -gt 1 ]
then
  usage
fi

backups=$(
  printf '%s\n' "${backups[@]}" | \
    cut -d' ' -f1 | \
    while read -r dir; do \
      if [ $(ls "$dir" | wc -l) -lt 30 ]; then
        continue;
      fi
      ls -1 "$dir" | \
        sed -n '
          s,^\([0-9]\{4\}\)_\([0-9]\{2\}\)_\([0-9]\{2\}\)$,'"${dir}"'\0 \3 \2 \1 '"${dir}"',
          T
          p
        '
    done
)

{
  printf '%s\n' "${backups}" | \
    sort -k5,5 -k4,4 -k3,3 -k2,2 -k1,1 | \
    uniq -f2
  printf '%s\n' "${backups}" | \
    sed '
      / '"$(date +%Y)"' \S\+$/p
    '
} | \
  cut -d' ' -f1 | \
  sort | \
  uniq -u | \
  while read -r dir; do
    echo rm -rf --one-file-system "${dir}"
    rm -rf --one-file-system "${dir}"
  done