aboutsummaryrefslogtreecommitdiff
path: root/cleaner.in
blob: 035892f7c68de37470a118333333dc7c31d70729 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#! /bin/sh

libdir=@LIBDIR@/beam
set -e
. $libdir/common.sh
set +e

dir=
suffix=
retainweeks=3
dry_run=
verbose=:

help() {
  cat <<EOF
usage: $0 [OPTIONS] DIR
cleans up old backup files in DIR

OPTIONS are:
  -s, --suffix SUF        consider only file names ending in SUF
  -r, --retain N          retain N last weeks of backups (default $retainweeks)
  -v, --verbose           verbosely list what is being done
  -n, --dry-run           do nothing, print what would have been done
  -h, --help              print this help list

EOF
  exit 0
}

while [ $# -ne 0 ]
do
  case $1 in
  -s|--suffix) shift; suffix=$1;;
  -r|--retain) shift; retainweeks=$1;;
  -v|--verbose) verbose=echo;;
  -n|--dry-run) dry_run=echo; verbose=echo;;
  -h|--help) help;;
  --wtf) wtf $(basename $0) clean up old files; exit 0;;
  --) shift; break;;
  -*) echo >&2 "$0: unrecognized option $1"
      exit 1;;
  *)  break
  esac
  shift
done

case $# in
0) echo >&2 "$0: not enough arguments"
   exit 1;;
1) dir=$1;;
*) echo >&2 "$0: too many arguments"
   exit 1;;
esac

thisweek=$(date +%U)

# Warning: do not use shell arithmetic expansions on week numbers,
# because weeks prior to 10 begin with 0 and therefore are processed
# as octal numbers.  This causes grief for weeks 08 and 09.
if [ $thisweek -gt $retainweeks ]; then
   lastweek=$(expr $thisweek - $retainweeks)
else
   lastweek=$(expr $thisweek + 54 - $retainweeks)
fi
   
$verbose \# removing from $dir files ending in $suffix and older than week $lastweek

if [ -z "$suffix" ]; then
  find $dir -maxdepth 1 -type f -printf '%f\n' 
else
  find $dir -maxdepth 1 -type f -name "*$suffix" -printf '%f\n' 
fi | 
 while read name
 do 
   $verbose \# considering $name 
   week=$(expr "$name" : '[^-][^-]*-\([0-9][0-9]*\)-.*')
   if [ $thisweek -ge $week ]; then
       if [ $(expr $thisweek - $week) -gt $retainweeks ]; then
	   $verbose \# removing $name
	   $dry_run rm $dir/$name
       fi
   else
       if [ $(expr $thisweek + 54 - $week) -gt $retainweeks ]; then
	   $verbose \# removing $name
	   $dry_run rm $dir/$name
       fi
   fi
 done

Return to:

Send suggestions and report system problems to the System administrator.