implement first_time($identifier) with Storable
[pxelator] / lib / PXElator / upstream.pm
1 package upstream;
2
3 use warnings;
4 use strict;
5 use autodie;
6
7 use LWP::Simple qw/mirror RC_NOT_MODIFIED/;
8 use Storable;
9 use server;
10
11 sub mirror_file {
12         my ( $url, $file ) = @_;
13         print STDERR "mirror $url";
14         mirror( $url, $file )
15                 == RC_NOT_MODIFIED
16                 && warn(" not modified\n")
17                 || warn(" done ", -s $file, " bytes\n")
18                 ;
19 }
20
21 my $once_path = '/tmp/pxelator.once';
22 our $just_once = retrieve $once_path;
23 sub first_time {
24         my $what = shift;
25         return if $just_once->{$what}++;
26         store $just_once, $once_path;
27         return 1;
28 }
29
30 sub iso {
31         my $url = shift;
32
33         return if ! first_time($url);
34
35         my $name = (caller(1))[3];
36         $name =~ s{config::}{} || die "caller isn't package config !";
37
38         warn "$name $url";
39
40         my $dir = "$server::base_dir/iso";
41         mkdir $dir unless -e $dir;
42
43         my $file = $1 if $url =~ m{/([^/]+\.iso$)}i;
44         die "can't find iso file in $url" unless $file;
45
46         my $iso = "$dir/$file";
47
48         mirror_file( $url, $iso );
49
50         $file =~ s{\.iso$}{}i;
51         my $mnt = "$server::base_dir/tftp/$name";
52         mkdir $mnt unless -d $mnt;
53         $mnt .= '/iso';
54         mkdir $mnt unless -d $mnt;
55
56         system("mount -t iso9660 | grep $name/iso || sudo mount $iso $mnt -o loop -t iso9660 -v") == 0;
57 }
58
59 sub files {
60         my $url = shift;
61
62         my $name = (caller(1))[3];
63         $name =~ s{config::}{} || die "caller isn't package config !";
64
65         my $path = "$server::base_dir/tftp/$name";
66
67         foreach my $file ( @_ ) {
68                 mirror_file "$url/$file", "$path/$file"
69                         if first_time( "$url/$file" );
70         }
71 }
72
73 sub mkpath {
74         my $file = shift;
75
76         my @file_parts = split m{/}, $file;
77         foreach ( 1 .. $#file_parts - 1 ) {
78                 my $path = splice @file_parts, 0, $_;
79                 warn "? $path\n";
80                 mkdir $path unless -e $path;
81         }
82 }
83
84 1;