]> Untitled Git - public.git/blob - public
Fixed to use ENV variables instead of hardcoded values
[public.git] / public
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 use File::Spec;
6 use File::Path qw/ make_path /;
7
8 my $root_dir = $ENV{PUBLIC_ROOT_DIR}
9         or die "Need PUBLIC_ROOT_DIR\n";
10 my $link_dir = $ENV{PUBLIC_LINK_DIR}
11         or die "Need PUBLIC_LINK_DIR\n";
12 my $http_uri = $ENV{PUBLIC_HTTP_URI}
13         or die "Need PUBLIC_HTTP_URI\n";
14
15
16 sub nonce {
17         my $n = shift;
18         $n = 10 unless $n > 0;
19
20         my @chars = ( 'a' .. 'z', 'A' .. 'Z', '0' .. '9' );
21         my @path = ();
22         push @path, $chars[ rand @chars ] for 1 .. $n;
23
24         return join '', @path;
25 }
26
27 sub makeNonceDir {
28         my $nonce = shift;
29         my $path  = File::Spec->catdir($link_dir, $nonce);
30         make_path($path, { chmod => 0777 });
31         return $path, ;
32 }
33
34 sub addFiles {
35         # get list of files matching name from root directory
36         my $name = shift
37                 or die "Need filename!\n";
38
39         opendir DIR, $root_dir;
40         my @files = grep /$name/i, readdir(DIR);
41         closedir DIR;
42
43         # exit if no files found
44         die "No match: $name\n" unless @files;
45
46         # create nonce dir and add symbolic links
47         my $nonce = nonce(20);
48         my $nonce_dir = makeNonceDir($nonce);
49
50         for my $file (@files) {
51                 my $root_filepath = File::Spec->catfile($root_dir,  $file);
52                 my $link_filepath = File::Spec->catfile($nonce_dir, $file);
53
54                 symlink $root_filepath, $link_filepath
55                         or die "Unable to create symlink: $root_filepath -> $link_filepath";
56
57                 my $uri_link = join '/', $http_uri, $nonce, $file;
58                 print "$uri_link\n";
59         }
60 }
61
62 sub listFiles {
63         opendir DIR, $link_dir;
64         my @nonces = readdir(DIR);
65         closedir DIR;
66
67         for my $nonce (@nonces) {
68                 next if $nonce eq '.';
69                 next if $nonce eq '..';
70
71                 # ensure it's a directory
72                 my $nonce_dir = File::Spec->catdir($link_dir, $nonce);
73                 next unless -d $nonce_dir;
74
75                 # make URIs for all the files in the nonce dirs
76                 opendir DIR, $nonce_dir;
77                 my @files = readdir(DIR);
78                 closedir DIR;
79
80                 for my $file (@files) {
81                         next if $file eq '.';
82                         next if $file eq '..';
83
84                         my $uri_link = join '/', $http_uri, $nonce, $file;
85                         print "$uri_link\n";
86                 }
87         }
88 }
89
90
91 # script begins
92 if (@ARGV) {
93         addFiles($_) for @ARGV;
94 }
95 else {
96         listFiles;
97 }