]> git.donarmstrong.com Git - infobot.git/blob - scripts/webbackup.pl
* Add vim formatting comments ( # vim:ts=4:sw=4:expandtab:tw=80 )
[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     } else {
31         print "error: failure.\n";
32         exit 1;
33     }
34 }
35
36 #...
37 if ( -f "$backup_destdir/$backup_indexfile") {
38     if (open(INDEX, "$backup_destdir/$backup_indexfile")) {
39         while (<INDEX>) {
40             chop;
41
42             # days since 1970, file.
43             if (/^(\d+) (\S+)$/) {
44                 $index{$1} = $2;
45             }
46         }
47         close INDEX;
48     } else {
49         print "WARNING: can't open $backup_indexfile.\n";
50     }
51 }
52 my $now_days    = (localtime)[7] + (((localtime)[5] - 70) * 365);
53 my $now_date    = strftime("%Y%m%d", localtime);
54
55 if (scalar keys %index) {
56     my $last_days       = (sort {$b <=> $a} keys %index)[0];
57
58     if ($now_days - $last_days < $backup_interval) {
59         print "error: shouldn't run today.\n";
60         goto cycle;
61     }
62 }
63
64 $backup_file =~ s/##DATE/$now_date/;
65 print "backup_file => '$backup_file'.\n";
66 if ( -f $backup_file) {
67     print "error: $backup_file already exists.\n";
68     exit 1;
69 }
70
71 my $file = &getURL($backup_url);
72 open(OUT,">$backup_destdir/$backup_file");
73 print OUT $file;
74 close OUT;
75
76 $index{$now_days} = $backup_file;
77 cycle:;
78 my @index = sort {$b <=> $a} keys %index;
79
80 open(OUT,">$backup_destdir/$backup_indexfile");
81 for(my $i=0; $i<scalar(@index); $i++) {
82     my $day = $index[$i];
83     print "fe: day => '$day'.\n";
84
85     if ($backup_count - 1 >= $i) {
86         print "DEBUG: $day $index{$day}\n";
87         print OUT "$day $index{$day}\n";
88     } else {
89         print "Deleting $index{$day}\n";
90         unlink $backup_destdir."/".$index{$day};
91     }
92 }
93 close OUT;
94
95 print "Done.\n";
96
97 # vim:ts=4:sw=4:expandtab:tw=80