]> git.donarmstrong.com Git - infobot.git/blob - scripts/webbackup.pl
dunno
[infobot.git] / scripts / webbackup.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use LWP;
5 use POSIX qw(strftime);
6
7 my $backup_interval = 1;    # every: 1,7,14,30.
8 my $backup_count    = 7;
9 my $backup_url       = "http://core.junker.org/~apt/tables.tar.bz2";
10 my $backup_file      = "tables-##DATE.tar.bz2";
11 my $backup_destdir   = "/home/xk/public_html/";
12 my $backup_indexfile = "tables-index.txt";
13
14 my %index;
15
16 # Usage: &getURL($url);
17 sub getURL {
18     my ($url) = @_;
19     my ( $ua, $res, $req );
20
21     $ua = new LWP::UserAgent;
22 ###    $ua->proxy('http', $proxy);
23
24     $req = new HTTP::Request( 'GET', $url );
25     $res = $ua->request($req);
26
27     # return NULL upon error.
28     if ( $res->is_success ) {
29         return $res->content;
30     }
31     else {
32         print "error: failure.\n";
33         exit 1;
34     }
35 }
36
37 #...
38 if ( -f "$backup_destdir/$backup_indexfile" ) {
39     if ( open( INDEX, "$backup_destdir/$backup_indexfile" ) ) {
40         while (<INDEX>) {
41             chop;
42
43             # days since 1970, file.
44             if (/^(\d+) (\S+)$/) {
45                 $index{$1} = $2;
46             }
47         }
48         close INDEX;
49     }
50     else {
51         print "WARNING: can't open $backup_indexfile.\n";
52     }
53 }
54 my $now_days = (localtime)[7] + ( ( (localtime)[5] - 70 ) * 365 );
55 my $now_date = strftime( "%Y%m%d", localtime );
56
57 if ( scalar keys %index ) {
58     my $last_days = ( sort { $b <=> $a } keys %index )[0];
59
60     if ( $now_days - $last_days < $backup_interval ) {
61         print "error: shouldn't run today.\n";
62         goto cycle;
63     }
64 }
65
66 $backup_file =~ s/##DATE/$now_date/;
67 print "backup_file => '$backup_file'.\n";
68 if ( -f $backup_file ) {
69     print "error: $backup_file already exists.\n";
70     exit 1;
71 }
72
73 my $file = &getURL($backup_url);
74 open( OUT, ">$backup_destdir/$backup_file" );
75 print OUT $file;
76 close OUT;
77
78 $index{$now_days} = $backup_file;
79 cycle:;
80 my @index = sort { $b <=> $a } keys %index;
81
82 open( OUT, ">$backup_destdir/$backup_indexfile" );
83 for ( my $i = 0 ; $i < scalar(@index) ; $i++ ) {
84     my $day = $index[$i];
85     print "fe: day => '$day'.\n";
86
87     if ( $backup_count - 1 >= $i ) {
88         print "DEBUG: $day $index{$day}\n";
89         print OUT "$day $index{$day}\n";
90     }
91     else {
92         print "Deleting $index{$day}\n";
93         unlink $backup_destdir . "/" . $index{$day};
94     }
95 }
96 close OUT;
97
98 print "Done.\n";
99
100 # vim:ts=4:sw=4:expandtab:tw=80