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