chiark / gitweb /
expire-iso8601: tidy docs and exit status
[chiark-utils.git] / scripts / expire-iso8601
1 #!/usr/bin/perl -w
2 #
3 # Copyright 2006 Ian Jackson <ijackson@chiark.greenend.org.uk>
4 #
5 # This script and its documentation (if any) are free software; you
6 # can redistribute it and/or modify them under the terms of the GNU
7 # General Public License as published by the Free Software Foundation;
8 # either version 3, or (at your option) any later version.
9
10 # chiark-named-conf and its manpage are distributed in the hope that
11 # it will be useful, but WITHOUT ANY WARRANTY; without even the
12 # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
13 # PURPOSE.  See the GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, consult the Free Software Foundation's
17 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
18
19 use strict;
20
21 our $usage = <<'END';
22 usage:
23   expire-iso8601 [<options>] <number>x<interval> [<number>x<interval> ...]
24 options:
25    -u<unitlen>  <interval> is measured in units of <unitlen> seconds
26                    (default is 86400, so <interval> is in days)
27    -s<slop>       allow kept items to be <slop> seconds shorter or
28                    longer apart than specified; default is 0.1 unit
29    -n             do not really delete
30    -r             recursive removal (rm -r)
31    --help
32 example:
33    /home/ian/junk/expire-iso8601 14x1 4x7
34       uses units of 86400s (1 day) with a slop of 8640
35       it keeps 14 daily items
36        (that is 14 items, dated no less than 86400-8640 apart)
37       and 4 weekly items
38        (that is 4 items, dated no less than 7*86400-8640 apart)
39       the 14 daily and 7 weekly items may be the same, or not
40    There is no need to sort the list of <number>x<interval> pairs.
41 exit status:
42    0                   ok
43    4                   rm failed
44    8                   bad usage
45   -1                   catastrophic failure
46 END
47
48 use POSIX;
49 use Carp;
50 use Data::Dumper;
51 use Date::Parse;
52 use DateTime::Format::Strptime;
53
54 $|=1;
55
56 our @oldfiles;
57 our @files;
58 our $rm = 1;
59 our $recurse = 1;
60 our $unit = 86400;
61 our $slop;
62 our $debug = 0;
63 our @intervals;
64
65 sub badusage ($) {
66   print STDERR "bad usage: $_[0]\n$usage" or die $!;
67   exit 8;
68 }
69
70 sub scan () {
71 #  my $strp = DateTime::Format::Strptime->new();
72   foreach my $f (<[0-9]*>) {
73     if ($f  !~ m/^ \d\d\d\d - \d\d - \d\d 
74                  (?: T \d\d \: \d\d (?: \: \d\d )?
75                    (?: [-+] \d{1,2} \:? \d\d )? )? 
76                  ( \.rm )? $/x) {
77       print STDERR "ignoring $f\n";
78     }
79
80     if ($1) {
81       push @oldfiles, $f;
82       next;
83     }
84
85     my @t = Date::Parse::strptime($f);
86     @t = map { $_ // 0 } @t;
87     my $t = mktime @t;
88 #    m
89 #    my $t = $strp->parse_datetime($f);
90 #    $t = $t->epoch();
91 #    my @t = Date::Parse::strptime($f);
92 #print STDERR Dumper(\@t);
93 #    my $t = mktime(@t);
94 #    $!=0; $?=0; my $t = `date -d '$&' +%s`;
95 #    die "date(!) failed on $&: $? $!" if $! || $?;
96 #    chomp $t or confess;
97     push @files, { F => $f, T => $t, U => [] };
98   }
99 }
100
101 sub precomp () {
102   if (!@files) {
103     print STDERR "none at all yet!\n";
104     exit 0;
105   }
106
107   # newest first, which means biggest T
108   @files = sort { $b->{T} <=> $a->{T} || $b->{F} cmp $a->{F} } @files;
109   my $newest_t = $files[0]{T};
110   $_->{A} = ($newest_t - $_->{T}) / $unit foreach @files;
111   $slop /= $unit;
112
113   push @{$files[0]{U}}, "newest";
114
115   print DEBUG Dumper(scalar(@files), \@files, \@intervals) if $debug >= 2;
116 }
117
118 sub flag ($) {
119   my ($int) = @_;
120   my $n = $int->{N};
121   my $d = $int->{D};
122   my $dmin = $d - $slop;
123   my $dmax = $d + $slop;
124   my $spec = $int->{Spec};
125   my $start_age = ($n-1) * $d - $slop;
126   my $i = 0;
127   my $insufficiently_old = 0;
128
129   print DEBUG "FLAG $spec sa=$start_age dmin=$dmin dmax=$dmax\n";
130
131   # find $i, the youngest which is at least $start_age
132   for (;;) {
133     print DEBUG "i #$i $files[$i]{A}\n";
134     last if $files[$i]{A} >= $start_age;
135     if ($i == $#files) {
136       $insufficiently_old = 1;
137       print STDERR "insufficiently old for $spec\n";
138       last;
139     }
140     $i++;
141   }
142
143   my $oldest = $i;
144   my $count = 0;
145
146   my $use = sub {
147     my ($i, $spec) = @_;
148     push @{ $files[$i]{U} }, $spec;
149     $count++;
150   };
151
152   for (;;) {
153     $use->($i, $spec);
154
155     # find $j, the closest to $i, preferably no more than $dmax younger
156     my $j = $i;
157     for (;;) {
158       $j--;
159       # at each point in this loop $j is the next candidate
160       last if $j < 0;
161       my $dt = $files[$i]{A} - $files[$j]{A};
162       print DEBUG "j #$j $files[$j]{A} dt=$dt\n";
163       last if $dt > $dmax;
164     }
165     $j++;
166     if ($j == $i) {
167       $j--;
168       print STDERR "insufficiently dense for $spec after $files[$j]{F}\n";
169       last if $j < 0;
170     }
171     print DEBUG "i #$j\n";
172
173     $i = $j;
174   }
175
176   $i = $oldest;
177   while ($count < $n) {
178     for (;;) {
179       $i++;
180       if ($i > $#files) {
181         if (!$insufficiently_old) {
182           print STDERR
183             "insufficiently old for $spec (density compensation)\n";
184         }
185         return;
186       }
187       my $dt = $files[$i]{A} - $files[$oldest]{A};
188       print DEBUG "o #$i $files[$i]{A} dt=$dt\n";
189       last if $dt >= $dmin;
190     }
191     $use->($i, "$spec+");
192   }
193 }
194
195 sub do_rm ($) {
196   my ($fn) = @_;
197   if ($rm) {
198     my $r= system 'rm', ($recurse ? ('-r') : ()), "--", $fn;
199     die "run rm: $!\n" unless defined($r) && $r >= 0;
200     exit 4 if $r;
201   }
202 }
203
204 sub implement () {
205   foreach (reverse sort @oldfiles) {
206     printf "remove %s - old\n", $_;
207     do_rm($_);
208   }
209   foreach (reverse @files) {
210     next unless @{$_->{U}};
211     printf "keep %s for %s - age %.1f\n",
212       $_->{F}, "@{$_->{U}}", $_->{A};
213   }
214   foreach (reverse @files) {
215     next if @{$_->{U}};
216     printf "remove %s - age %.1f\n",
217       $_->{F}, $_->{A};
218     if ($rm) {
219       my $tmp = "$_->{F}.rm";
220       rename $_->{F}, $tmp or die "rename $_->{F} to $tmp: $!\n";
221       do_rm($tmp);
222     }
223   }
224 }
225
226 open DEBUG, ">/dev/null" or die $!;
227
228 while (@ARGV && $ARGV[0] =~ m/^-/) {
229   $_ = shift @ARGV;
230   last if $_ eq '-' || $_ eq '--';
231   if (m/^-[^-]/) {
232     while (m/^-./) {
233       if (s/^-n/-/) { $rm=0; }
234       elsif (s/-r/-/) { $recurse=1; }
235       elsif (s/-D/-/) { $debug++; }
236       elsif (s/-u(\d+)$//) { $unit=$1; }
237       elsif (s/-s(\d+)$//) { $slop=$1; }
238       else { badusage "unknown short option $_" }
239     }
240   } elsif (m/^--help$/) {
241     print $usage or die $!;
242     exit 0;
243   } else {
244     badusage "unknown long option $_"
245   }
246 }
247
248 badusage "too few arguments" unless @ARGV;
249
250 if ($debug) {
251   open DEBUG, ">&STDERR" or die $!;
252   DEBUG->autoflush(1);
253 }
254
255 $slop //= $unit * 0.1;
256
257 foreach (@ARGV) {
258   m/^(\d+)x(\d+)$/ or badusage "bad <number>x<interval> $_";
259   push @intervals, { Spec => $&, N => $1, D => $2 };
260 }
261
262 scan();
263 precomp();
264 foreach (@intervals) { flag $_ }
265 implement();