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