add master mirror to download script
[openwrt-10.03/.git] / scripts / download.pl
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 my $target = shift @ARGV;
6 my $filename = shift @ARGV;
7 my $md5sum = shift @ARGV;
8 my @mirrors = @ARGV;
9
10 my $ok;
11
12 @mirrors > 0 or die "Syntax: $0 <target dir> <filename> <md5sum> <mirror> [<mirror> ...]\n";
13
14 push @mirrors, 'http://openwrt.inf.fh-brs.de/mirror';
15
16 sub download
17 {
18         my $mirror = shift;
19         
20         open WGET, "wget -t1 --timeout=20 -O- \"$mirror/$filename\" |" or die "Cannot launch wget.\n";
21         open MD5SUM, "| md5sum > \"$target/$filename.md5sum\"" or die "Cannot launch md5sum.\n";
22         open OUTPUT, "> $target/$filename.dl" or die "Cannot create file $target/$filename.dl: $!\n";
23         my $buffer;
24         while (read WGET, $buffer, 1048576) {
25                 print MD5SUM $buffer;
26                 print OUTPUT $buffer;
27         }
28         close MD5SUM;
29         close WGET;
30         close OUTPUT;
31         
32         if (($? >> 8) != 0 ) {
33                 print STDERR "Download failed.\n";
34                 cleanup();
35                 return;
36         }
37         
38         my $sum = `cat "$target/$filename.md5sum"`;
39         $sum =~ /^(\w+)\s+/ or die "Could not generate md5sum\n";
40         $sum = $1;
41         
42         if (($md5sum =~ /\w{32}/) and ($sum ne $md5sum)) {
43                 print STDERR "MD5 sum of the downloaded file does not match - deleting download.\n";
44                 cleanup();
45                 return;
46         }
47         
48         unlink "$target/$filename";
49         system("mv \"$target/$filename.dl\" \"$target/$filename\"");
50         cleanup();
51 }
52
53 sub cleanup
54 {
55         unlink "$target/$filename.dl";
56         unlink "$target/$filename.md5sum";
57 }
58
59 while (!$ok) {
60         my $mirror = shift @mirrors;
61         $mirror or die "No more mirrors to try - giving up.\n";
62         
63         if ($mirror =~ /^\@SF\/(.+)$/) {
64                 my $sfpath = $1;
65                 open SF, "wget -t1 -q -O- 'http://prdownloads.sf.net/$sfpath/$filename' |";
66                 while (<SF>) {
67                         /RADIO NAME=use_default VALUE=(\w+) OnClick="form\.submit\(\)">/ and do {
68                                 push @mirrors, "http://$1.dl.sourceforge.net/sourceforge/$sfpath";
69                         };
70                 }
71                 close SF;
72         } else {
73                 download($mirror);
74         }
75         -f "$target/$filename" and $ok = 1;
76 }
77
78 $SIG{INT} = \&cleanup;
79