]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
lei_mirror: set info/web/last-modified from manifest
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use v5.12;
7 use parent qw(PublicInbox::IPC);
8 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
9 use IO::Compress::Gzip qw(gzip $GzipError);
10 use PublicInbox::Spawn qw(popen_rd spawn run_die);
11 use File::Path ();
12 use File::Temp ();
13 use File::Spec ();
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
15 use Carp qw(croak);
16 use URI;
17 use PublicInbox::Config;
18 use PublicInbox::Inbox;
19 use PublicInbox::LeiCurl;
20 use PublicInbox::OnDestroy;
21 use Digest::SHA qw(sha256_hex sha1_hex);
22 use POSIX qw(strftime);
23
24 our $LIVE; # pid => callback
25 our $FGRP_TODO; # objstore -> [ fgrp mirror objects ]
26 our $TODO; # reference => [ non-fgrp mirror objects ]
27
28 sub keep_going ($) {
29         $LIVE && (!$_[0]->{lei}->{child_error} ||
30                 $_[0]->{lei}->{opt}->{'keep-going'});
31 }
32
33 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
34         my ($arg, $pid) = @_;
35         my ($mrr, $lei) = @$arg;
36         if ($?) {
37                 $lei->child_error($?);
38         } elsif (!$lei->{child_error}) {
39                 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
40                         require PublicInbox::LeiAddExternal;
41                         PublicInbox::LeiAddExternal::_finish_add_external(
42                                                         $lei, $mrr->{dst});
43                 }
44                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
45         }
46         $lei->dclose;
47 }
48
49 # for old installations without manifest.js.gz
50 sub try_scrape {
51         my ($self, $fallback_manifest) = @_;
52         my $uri = URI->new($self->{src});
53         my $lei = $self->{lei};
54         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
55         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
56         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
57         my $fh = popen_rd($cmd, undef, $opt);
58         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
59         close($fh) or return $lei->child_error($?, "@$cmd failed");
60
61         # we grep with URL below, we don't want Subject/From headers
62         # making us clone random URLs.  This assumes remote instances
63         # prior to public-inbox 1.7.0
64         # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
65         my @html = split(/<hr>/, $html);
66         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
67         if (!@urls && $fallback_manifest) {
68                 warn <<EOM;
69 W: failed to extract URLs from $uri, trying manifest.js.gz...
70 EOM
71                 return start_clone_url($self);
72         }
73         my $url = $uri->as_string;
74         chop($url) eq '/' or die "BUG: $uri not canonicalized";
75
76         # since this is for old instances w/o manifest.js.gz, try v1 first
77         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
78         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
79                 my %v2_epochs = map {
80                         my ($n) = (m!/([0-9]+)\z!);
81                         $n => [ URI->new($_), '' ]
82                 } @v2_urls; # uniq
83                 clone_v2_prep($self, \%v2_epochs);
84                 delete local $lei->{opt}->{epoch};
85                 clone_all($self);
86                 return;
87         }
88
89         # filter out common URLs served by WWW (e.g /$MSGID/T/)
90         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
91                         grep(m!\A\Q$url\E/*\z!, @urls)) {
92                 die <<"";
93 E: confused by scraping <$uri>, did you mean <$url>?
94
95         }
96         @urls and die <<"";
97 E: confused by scraping <$uri>, got ambiguous results:
98 @urls
99
100         die "E: scraping <$uri> revealed nothing\n";
101 }
102
103 sub clone_cmd {
104         my ($lei, $opt) = @_;
105         my @cmd = qw(git);
106         $opt->{$_} = $lei->{$_} for (0..2);
107         # we support "-c $key=$val" for arbitrary git config options
108         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
109         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
110         push @cmd, qw(clone --mirror);
111         push @cmd, '-q' if $lei->{opt}->{quiet} ||
112                         ($lei->{opt}->{jobs} // 1) > 1;
113         push @cmd, '-v' if $lei->{opt}->{verbose};
114         # XXX any other options to support?
115         # --reference is tricky with multiple epochs, but handled
116         # automatically if using manifest.js.gz
117         @cmd;
118 }
119
120 sub ft_rename ($$$;$) {
121         my ($ft, $dst, $open_mode, $fh) = @_;
122         my @st = stat($fh // $dst);
123         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
124         chmod($mode, $ft) or croak "E: chmod($ft): $!";
125         require File::Copy;
126         File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
127         $ft->unlink_on_destroy(0);
128 }
129
130 sub do_reap ($;$) {
131         my ($self, $jobs) = @_;
132         $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
133         $jobs = 1 if $jobs < 1;
134         while (keys(%$LIVE) >= $jobs) {
135                 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
136                 if (my $x = delete $LIVE->{$pid}) {
137                         my $cb = shift @$x;
138                         $cb->(@$x) if $cb;
139                 } else {
140                         warn "reaped unknown PID=$pid ($?)\n";
141                 }
142         }
143 }
144
145 sub _get_txt_start { # non-fatal
146         my ($self, $endpoint, $fini) = @_;
147         my $uri = URI->new($self->{cur_src} // $self->{src});
148         my $lei = $self->{lei};
149         my $path = $uri->path;
150         chop($path) eq '/' or die "BUG: $uri not canonicalized";
151         $uri->path("$path/$endpoint");
152         my $f = (split(m!/!, $endpoint))[-1];
153         my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
154         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
155         my $cmd = $self->{curl}->for_uri($lei, $uri, qw(--compressed -R -o),
156                                         $ft->filename);
157         do_reap($self);
158         $lei->qerr("# @$cmd");
159         return if $self->{dry_run};
160         $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
161         $LIVE->{spawn($cmd, undef, $opt)} =
162                         [ \&_get_txt_done, $self, $endpoint, $fini ];
163 }
164
165 sub _get_txt_done { # returns true on error (non-fatal), undef on success
166         my ($self, $endpoint) = @_;
167         my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
168         my $cerr = $?;
169         $? = 0; # don't influence normal lei exit
170         return warn("$uri missing\n") if ($cerr >> 8) == 22;
171         return warn("# @$cmd failed (non-fatal)\n") if $cerr;
172         seek($fh, SEEK_SET, 0) or die "seek: $!";
173         $self->{"mtime.$endpoint"} = (stat($fh))[9];
174         local $/;
175         $self->{"txt.$endpoint"} = <$fh>;
176         undef; # success
177 }
178
179 sub _write_inbox_config {
180         my ($self) = @_;
181         my $buf = delete($self->{'txt._/text/config/raw'}) // return;
182         my $dst = $self->{cur_dst} // $self->{dst};
183         my $f = "$dst/inbox.config.example";
184         open my $fh, '>', $f or die "open($f): $!";
185         print $fh $buf or die "print: $!";
186         chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
187         my $mtime = delete $self->{'mtime._/text/config/raw'};
188         $fh->flush or die "flush($f): $!";
189         if (defined $mtime) {
190                 utime($mtime, $mtime, $fh) or die "utime($f): $!";
191         }
192         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
193         my $ibx = $self->{ibx} = {};
194         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
195                 for (qw(address newsgroup nntpmirror)) {
196                         $ibx->{$_} = $cfg->{"$sec.$_"};
197                 }
198         }
199 }
200
201 sub set_description ($) {
202         my ($self) = @_;
203         my $dst = $self->{cur_dst} // $self->{dst};
204         chomp(my $orig = PublicInbox::Git::try_cat("$dst/description"));
205         my $d = $orig;
206         while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
207                         $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
208                 $d = delete($self->{'txt.description'});
209         }
210         $d //= 'mirror of '.($self->{cur_src} // $self->{src});
211         atomic_write($dst, 'description', $d."\n") if $d ne $orig;
212 }
213
214 sub index_cloned_inbox {
215         my ($self, $iv) = @_;
216         my $lei = $self->{lei};
217
218         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
219         # lei is useless without Xapian + SQLite
220         if ($lei->{cmd} ne 'public-inbox-clone') {
221                 require PublicInbox::InboxWritable;
222                 require PublicInbox::Admin;
223                 my $ibx = delete($self->{ibx}) // {
224                         address => [ 'lei@example.com' ],
225                         version => $iv,
226                 };
227                 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
228                 PublicInbox::Inbox->new($ibx);
229                 PublicInbox::InboxWritable->new($ibx);
230                 my $opt = {};
231                 for my $sw ($lei->index_opt) {
232                         my ($k) = ($sw =~ /\A([\w-]+)/);
233                         $opt->{$k} = $lei->{opt}->{$k};
234                 }
235                 # force synchronous dwaitpid for v2:
236                 local $PublicInbox::DS::in_loop = 0;
237                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
238                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
239                 local %ENV = (%ENV, %$env) if $env;
240                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
241                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
242         }
243         return if defined $self->{cur_dst}; # one of many repos to clone
244 }
245
246 sub run_reap {
247         my ($lei, $cmd, $opt) = @_;
248         $lei->qerr("# @$cmd");
249         waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
250         my $ret = $?;
251         $? = 0; # don't let it influence normal exit
252         $ret;
253 }
254
255 sub start_cmd {
256         my ($self, $cmd, $opt, $fini) = @_;
257         do_reap($self);
258         $self->{lei}->qerr("# @$cmd");
259         return if $self->{dry_run};
260         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
261 }
262
263 sub fetch_args ($$) {
264         my ($lei, $opt) = @_;
265         my @cmd; # (git --git-dir=...) to be added by caller
266         $opt->{$_} = $lei->{$_} for (0..2);
267         # we support "-c $key=$val" for arbitrary git config options
268         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
269         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
270         push @cmd, 'fetch';
271         push @cmd, '-q' if $lei->{opt}->{quiet} ||
272                         ($lei->{opt}->{jobs} // 1) > 1;
273         push @cmd, '-v' if $lei->{opt}->{verbose};
274         push(@cmd, '-p') if $lei->{opt}->{prune};
275         @cmd;
276 }
277
278 sub upr { # feed `git update-ref --stdin -z' verbosely
279         my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
280         $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
281         print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
282 }
283
284 sub fgrp_update {
285         my ($fgrp) = @_;
286         return if !keep_going($fgrp);
287         my $srcfh = delete $fgrp->{srcfh} or return;
288         my $dstfh = delete $fgrp->{dstfh} or return;
289         seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
290         seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
291         my %src = map { chomp; split(/\0/) } (<$srcfh>);
292         close $srcfh;
293         my %dst = map { chomp; split(/\0/) } (<$dstfh>);
294         close $dstfh;
295         pipe(my ($r, $w)) or die "pipe: $!";
296         my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
297                 qw(update-ref --stdin -z) ];
298         my $lei = $fgrp->{lei};
299         my $pack = PublicInbox::OnDestroy->new($$, \&pack_dst, $fgrp);
300         start_cmd($fgrp, $cmd, { 0 => $r, 2 => $lei->{2} }, $pack);
301         close $r or die "close(r): $!";
302         return if $fgrp->{dry_run};
303         for my $ref (keys %dst) {
304                 my $new = delete $src{$ref};
305                 my $old = $dst{$ref};
306                 if (defined $new) {
307                         $new eq $old or
308                                 upr($lei, $w, 'update', $ref, $new, $old);
309                 } else {
310                         upr($lei, $w, 'delete', $ref, $old);
311                 }
312         }
313         while (my ($ref, $oid) = each %src) {
314                 upr($lei, $w, 'create', $ref, $oid);
315         }
316         close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
317 }
318
319 sub pack_dst { # packs lightweight satellite repos
320         my ($fgrp) = @_;
321         pack_refs($fgrp, $fgrp->{cur_dst});
322 }
323
324 sub pack_refs {
325         my ($self, $git_dir) = @_;
326         my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
327         start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
328 }
329
330 sub fgrpv_done {
331         my ($fgrpv) = @_;
332         return if !$LIVE;
333         my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
334         return if !keep_going($first);
335         pack_refs($first, $first->{-osdir}); # objstore refs always packed
336         for my $fgrp (@$fgrpv) {
337                 my $rn = $fgrp->{-remote};
338                 my %opt = ( 2 => $fgrp->{lei}->{2} );
339
340                 my $update_ref = PublicInbox::OnDestroy->new($$,
341                                                         \&fgrp_update, $fgrp);
342
343                 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
344                         "--format=refs/%(refname:lstrip=3)%00%(objectname)",
345                         "refs/remotes/$rn/" ];
346                 open(my $sfh, '+>', undef) or die "open(src): $!";
347                 $fgrp->{srcfh} = $sfh;
348                 start_cmd($fgrp, $src, { %opt, 1 => $sfh }, $update_ref);
349                 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
350                         '--format=%(refname)%00%(objectname)' ];
351                 open(my $dfh, '+>', undef) or die "open(dst): $!";
352                 $fgrp->{dstfh} = $dfh;
353                 start_cmd($fgrp, $dst, { %opt, 1 => $dfh }, $update_ref);
354         }
355 }
356
357 sub fgrp_fetch_all {
358         my ($self) = @_;
359         my $todo = $FGRP_TODO;
360         $FGRP_TODO = \'BUG on further use';
361         keys(%$todo) or return;
362
363         # Rely on the fgrptmp remote groups in the config file rather
364         # than listing all remotes since the remote name list may exceed
365         # system argv limits:
366         my $grp = 'fgrptmp';
367
368         my @git = (@{$self->{-torsocks}}, 'git');
369         my $j = $self->{lei}->{opt}->{jobs};
370         my $opt = {};
371         my @fetch = do {
372                 local $self->{lei}->{opt}->{jobs} = 1;
373                 (fetch_args($self->{lei}, $opt),
374                         qw(--no-tags --multiple));
375         };
376         push(@fetch, "-j$j") if $j;
377         while (my ($osdir, $fgrpv) = each %$todo) {
378                 my $f = "$osdir/config";
379
380                 # clobber group from previous run atomically
381                 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
382                                 $f, '--unset-all', "remotes.$grp"];
383                 $self->{lei}->qerr("# @$cmd");
384                 if (!$self->{dry_run}) {
385                         my $pid = spawn($cmd, undef, { 2 => $self->{lei}->{2} });
386                         waitpid($pid, 0) // die "waitpid: $!";
387                         die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
388
389                         # update the config atomically via O_APPEND while
390                         # respecting git-config locking
391                         sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
392                                 or die "open($f.lock): $!";
393                         open my $fh, '>>', $f or die "open(>>$f): $!";
394                         $fh->autoflush(1);
395                         my $buf = join('', "[remotes]\n",
396                                 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
397                         print $fh $buf or die "print($f): $!";
398                         close $fh or die "close($f): $!";
399                         unlink("$f.lock") or die "unlink($f.lock): $!";
400                 }
401
402                 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
403                 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
404                 start_cmd($self, $cmd, $opt, $end);
405         }
406 }
407
408 # keep this idempotent for future use by public-inbox-fetch
409 sub forkgroup_prep {
410         my ($self, $uri) = @_;
411         $self->{-ent} // return;
412         my $os = $self->{-objstore} // return;
413         my $fg = $self->{-ent}->{forkgroup} // return;
414         my $dir = "$os/$fg.git";
415         if (!-d $dir && !$self->{dry_run}) {
416                 PublicInbox::Import::init_bare($dir);
417                 my @cmd = ('git', "--git-dir=$dir", 'config');
418                 my $opt = { 2 => $self->{lei}->{2} };
419                 for ('repack.useDeltaIslands=true',
420                                 'pack.island=refs/remotes/([^/]+)/') {
421                         run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
422                 }
423         }
424         my $key = $self->{-key} // die 'BUG: no -key';
425         my $rn = substr(sha256_hex($key), 0, 16);
426         if (!-d $self->{cur_dst} && !$self->{dry_run}) {
427                 my $alt = File::Spec->rel2abs("$dir/objects");
428                 PublicInbox::Import::init_bare($self->{cur_dst});
429                 my $o = "$self->{cur_dst}/objects";
430                 my $f = "$o/info/alternates";
431                 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
432                 open my $fh, '+>>', $f or die "open($f): $!";
433                 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
434                 chomp(my @cur = <$fh>);
435                 if (!grep(/\A\Q$l\E\z/, @cur)) {
436                         say $fh $l or die "say($f): $!";
437                 }
438                 close $fh or die "close($f): $!";
439                 $f = "$self->{cur_dst}/config";
440                 open $fh, '+>>', $f or die "open:($f): $!";
441                 print $fh <<EOM or die "print($f): $!";
442 ; rely on the "$rn" remote in the
443 ; $fg fork group for fetches
444 ; only uncomment the following iff you detach from fork groups
445 ; [remote "origin"]
446 ;       url = $uri
447 ;       fetch = +refs/*:refs/*
448 ;       mirror = true
449 EOM
450                 close $fh or die "close($f): $!";
451         }
452         bless {
453                 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
454         }, __PACKAGE__;
455 }
456
457 sub fp_done {
458         my ($self, $cb, @arg) = @_;
459         return if !keep_going($self);
460         my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
461         seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
462         $self->{-ent} // die 'BUG: no -ent';
463         my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
464         my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
465         return $cb->($self, @arg) if $A ne $B;
466         $self->{lei}->qerr("# $self->{-key} up-to-date");
467 }
468
469 sub cmp_fp_do {
470         my ($self, $cb, @arg) = @_;
471         # $cb is either resume_fetch or fgrp_enqueue
472         $self->{-ent} // return $cb->($self, @arg);
473         my $new = $self->{-ent}->{fingerprint} // return $cb->($self, @arg);
474         my $key = $self->{-key} // die 'BUG: no -key';
475         if (my $cur_ent = $self->{-local_manifest}->{$key}) {
476                 # runs go_fetch->DESTROY run if eq
477                 return if $cur_ent->{fingerprint} eq $new;
478         }
479         my $dst = $self->{cur_dst} // $self->{dst};
480         my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
481         my $opt = { 2 => $self->{lei}->{2} };
482         open($opt->{1}, '+>', undef) or die "open(tmp): $!";
483         $self->{-show_ref} = $opt->{1};
484         my $done = PublicInbox::OnDestroy->new($$, \&fp_done, $self, $cb, @arg);
485         start_cmd($self, $cmd, $opt, $done);
486 }
487
488 sub resume_fetch {
489         my ($self, $uri, $fini) = @_;
490         return if !keep_going($self);
491         my $dst = $self->{cur_dst} // $self->{dst};
492         my @git = ('git', "--git-dir=$dst");
493         my $opt = { 2 => $self->{lei}->{2} };
494         my $rn = 'origin'; # configurable?
495         for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
496                 my @kv = split(/=/, $_, 2);
497                 $kv[0] = "remote.$rn.$kv[0]";
498                 next if $self->{dry_run};
499                 run_die([@git, 'config', @kv], undef, $opt);
500         }
501         my $cmd = [ @{$self->{-torsocks}}, @git,
502                         fetch_args($self->{lei}, $opt), $rn ];
503         push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
504         start_cmd($self, $cmd, $opt, $fini);
505 }
506
507 sub fgrp_enqueue {
508         my ($fgrp, $end) = @_; # $end calls fgrp_fetch_all
509         return if !keep_going($fgrp);
510         my $opt = { 2 => $fgrp->{lei}->{2} };
511         # --no-tags is required to avoid conflicts
512         my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
513         my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
514         my @cmd = ('git', "--git-dir=$fgrp->{-osdir}", 'config');
515         for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*", 'tagopt=--no-tags') {
516                 my @kv = split(/=/, $_, 2);
517                 $kv[0] = "remote.$rn.$kv[0]";
518                 $fgrp->{dry_run} ? $fgrp->{lei}->qerr("# @cmd @kv") :
519                                 run_die([@cmd, @kv], undef, $opt);
520         }
521         push @{$FGRP_TODO->{$fgrp->{-osdir}}}, $fgrp;
522 }
523
524 sub clone_v1 {
525         my ($self, $end) = @_;
526         my $lei = $self->{lei};
527         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
528         my $uri = URI->new($self->{cur_src} // $self->{src});
529         my $path = $uri->path;
530         $path =~ s!/*\z!! and $uri->path($path);
531         defined($lei->{opt}->{epoch}) and
532                 die "$uri is a v1 inbox, --epoch is not supported\n";
533         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
534         my $dst = $self->{cur_dst} // $self->{dst};
535         my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
536         my $resume = -d $dst;
537         if (my $fgrp = forkgroup_prep($self, $uri)) {
538                 $fgrp->{-fini} = $fini;
539                 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue, $end)
540                         : fgrp_enqueue($fgrp, $end);
541         } elsif ($resume) {
542                 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
543         } else { # normal clone
544                 my $cmd = [ @{$self->{-torsocks}},
545                                 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
546                 if (defined($self->{-ent})) {
547                         if (defined(my $ref = $self->{-ent}->{reference})) {
548                                 -e "$self->{dst}$ref" and
549                                         push @$cmd, '--reference',
550                                                 "$self->{dst}$ref";
551                         }
552                 }
553                 start_cmd($self, $cmd, $opt, $fini);
554         }
555         if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
556                                 /\A(?:always|v1)\z/s) {
557                 _get_txt_start($self, '_/text/config/raw', $fini);
558         }
559
560         my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
561         $self->{'txt.description'} = $d if defined $d;
562         (!defined($d) && !$end) and
563                 _get_txt_start($self, 'description', $fini);
564
565         $end or do_reap($self, 1); # for non-manifest clone
566 }
567
568 sub parse_epochs ($$) {
569         my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
570         $opt_epochs // return; # undef => all epochs
571         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
572         undef($lo) if ($lo // '') eq '';
573         my $re = qr/\A~?[0-9]+\z/;
574         if (@extra || (($lo // '0') !~ $re) ||
575                         (($hi // '0') !~ $re) ||
576                         !(grep(defined, $lo, $hi))) {
577                 die <<EOM;
578 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
579 EOM
580         }
581         my @n = sort { $a <=> $b } keys %$v2_epochs;
582         for (grep(defined, $lo, $hi)) {
583                 if (/\A[0-9]+\z/) {
584                         $_ > $n[-1] and die
585 "`$_' exceeds maximum available epoch ($n[-1])\n";
586                         $_ < $n[0] and die
587 "`$_' is lower than minimum available epoch ($n[0])\n";
588                 } elsif (/\A~([0-9]+)/) {
589                         my $off = -$1 - 1;
590                         $n[$off] // die "`$_' is out of range\n";
591                         $_ = $n[$off];
592                 } else { die "`$_' not understood\n" }
593         }
594         defined($lo) && defined($hi) && $lo > $hi and die
595 "low value (`$lo') exceeds high (`$hi')\n";
596         $lo //= $n[0] if $dotdot;
597         $hi //= $n[-1] if $dotdot;
598         $hi //= $lo;
599         my $want = {};
600         for ($lo..$hi) {
601                 if (defined $v2_epochs->{$_}) {
602                         $want->{$_} = 1;
603                 } else {
604                         warn
605 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
606                 }
607         }
608         $want
609 }
610
611 sub init_placeholder ($$$) {
612         my ($src, $edst, $ent) = @_;
613         PublicInbox::Import::init_bare($edst);
614         my $f = "$edst/config";
615         open my $fh, '>>', $f or die "open($f): $!";
616         print $fh <<EOM or die "print($f): $!";
617 [remote "origin"]
618         url = $src
619         fetch = +refs/*:refs/*
620         mirror = true
621
622 ; This git epoch was created read-only and "public-inbox-fetch"
623 ; will not fetch updates for it unless write permission is added.
624 ; Hint: chmod +w $edst
625 EOM
626         if (defined($ent->{owner})) {
627                 print $fh <<EOM or die "print($f): $!";
628 [gitweb]
629         owner = $ent->{owner}
630 EOM
631         }
632         close $fh or die "close($f): $!";
633         my %map = (head => 'HEAD', description => undef);
634         while (my ($key, $fn) = each %map) {
635                 my $val = $ent->{$key} // next;
636                 $fn //= $key;
637                 $fn = "$edst/$fn";
638                 open $fh, '>', $fn or die "open($fn): $!";
639                 print $fh $val, "\n" or die "print($fn): $!";
640                 close $fh or die "close($fn): $!";
641         }
642 }
643
644 sub reap_cmd { # async, called via SIGCHLD
645         my ($self, $cmd) = @_;
646         my $cerr = $?;
647         $? = 0; # don't let it influence normal exit
648         $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
649 }
650
651 sub up_fp_done {
652         my ($self) = @_;
653         return if !keep_going($self);
654         my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
655         seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
656         $self->{-ent} // die 'BUG: no -ent';
657         my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
658         my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
659         return if $A eq $B;
660         $self->{-ent}->{fingerprint} = $B;
661         push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
662 }
663
664 sub atomic_write ($$$) {
665         my ($dn, $bn, $raw) = @_;
666         my $ft = File::Temp->new(DIR => $dn, TEMPLATE => "$bn-XXXX");
667         print $ft $raw or die "print($ft): $!";
668         $ft->flush or die "flush($ft): $!";
669         ft_rename($ft, "$dn/$bn", 0666);
670 }
671
672 # modifies the to-be-written manifest entry, and sets values from it, too
673 sub update_ent {
674         my ($self) = @_;
675         my $key = $self->{-key} // die 'BUG: no -key';
676         my $new = $self->{-ent}->{fingerprint};
677         my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
678         my $dst = $self->{cur_dst} // $self->{dst};
679         if (defined($new) && $new ne $cur) {
680                 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
681                 my $opt = { 2 => $self->{lei}->{2} };
682                 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
683                 $self->{-show_ref_up} = $opt->{1};
684                 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
685                 start_cmd($self, $cmd, $opt, $done);
686         }
687         $new = $self->{-ent}->{head};
688         $cur = $self->{-local_manifest}->{$key}->{head} // "\0";
689         if (defined($new) && $new ne $cur) {
690                 # n.b. grokmirror writes raw contents to $dst/HEAD w/o locking
691                 my $cmd = [ 'git', "--git-dir=$dst" ];
692                 if ($new =~ s/\Aref: //) {
693                         push @$cmd, qw(symbolic-ref HEAD), $new;
694                 } elsif ($new =~ /\A[a-f0-9]{40,}\z/) {
695                         push @$cmd, qw(update-ref --no-deref HEAD), $new;
696                 } else {
697                         undef $cmd;
698                         warn "W: $key: {head} => `$new' not understood\n";
699                 }
700                 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} }) if $cmd;
701         }
702         if (my $symlinks = $self->{-ent}->{symlinks}) {
703                 my $top = File::Spec->rel2abs($self->{dst});
704                 for my $p (@$symlinks) {
705                         my $ln = "$top/$p";
706                         $ln =~ tr!/!/!s;
707                         my (undef, $dn, $bn) = File::Spec->splitpath($ln);
708                         File::Path::mkpath($dn);
709                         my $tgt = "$top/$key";
710                         $tgt = File::Spec->abs2rel($tgt, $dn);
711                         if (lstat($ln)) {
712                                 if (-l _) {
713                                         next if readlink($ln) eq $tgt;
714                                         unlink($ln) or die "unlink($ln): $!";
715                                 } else {
716                                         push @{$self->{chg}->{badlink}}, $p;
717                                 }
718                         }
719                         symlink($tgt, $ln) or die "symlink($tgt, $ln): $!";
720                 }
721         }
722         if (defined(my $t = $self->{-ent}->{modified})) {
723                 my ($dn, $bn) = ("$dst/info/web", 'last-modified');
724                 my $orig = PublicInbox::Git::try_cat("$dn/$bn");
725                 $t = strftime('%F %T', gmtime($t))." +0000\n";
726                 File::Path::mkpath($dn);
727                 atomic_write($dn, $bn, $t) if $orig ne $t;
728         }
729
730         $new = $self->{-ent}->{owner} // return;
731         $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
732         return if $cur eq $new;
733         my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
734         start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
735 }
736
737 sub v1_done { # called via OnDestroy
738         my ($self) = @_;
739         return if $self->{dry_run} || !keep_going($self);
740         _write_inbox_config($self);
741         my $dst = $self->{cur_dst} // $self->{dst};
742         update_ent($self) if $self->{-ent};
743         my $o = "$dst/objects";
744         if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
745                 my $base = File::Spec->rel2abs($o);
746                 my @l = <$fh>;
747                 my $ft;
748                 for (@l) {
749                         next unless m!\A/!;
750                         $_ = File::Spec->abs2rel($_, $base);
751                         $ft //= File::Temp->new(TEMPLATE => '.XXXX',
752                                                 DIR => "$o/info");
753                 }
754                 if ($ft) {
755                         print $ft @l or die "print($ft): $!";
756                         $ft->flush or die "flush($ft): $!";
757                         ft_rename($ft, $fn, 0666, $fh);
758                 }
759         }
760         eval { set_description($self) };
761         warn $@ if $@;
762         return if ($self->{-is_epoch} ||
763                 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
764         write_makefile($dst, 1);
765         index_cloned_inbox($self, 1);
766 }
767
768 sub v2_done { # called via OnDestroy
769         my ($self) = @_;
770         return if $self->{dry_run} || !keep_going($self);
771         my $dst = $self->{cur_dst} // $self->{dst};
772         require PublicInbox::Lock;
773         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
774         my $lck = $lk->lock_for_scope($$);
775         _write_inbox_config($self);
776         require PublicInbox::MultiGit;
777         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
778         $mg->fill_alternates;
779         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
780         for my $edst (@{delete($self->{-read_only}) // []}) {
781                 my @st = stat($edst) or die "stat($edst): $!";
782                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
783         }
784         write_makefile($dst, 2);
785         undef $lck; # unlock
786         eval { set_description($self) };
787         warn $@ if $@;
788         index_cloned_inbox($self, 2);
789 }
790
791 sub clone_v2_prep ($$;$) {
792         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
793         my $lei = $self->{lei};
794         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
795         my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
796         $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
797         my $dst = $self->{cur_dst} // $self->{dst};
798         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
799         my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
800         my (@skip, $desc);
801         my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
802         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
803                 my ($uri, $key) = @{$v2_epochs->{$nr}};
804                 my $src = $uri->as_string;
805                 my $edst = $dst;
806                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
807 failed to extract epoch number from $src
808
809                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
810                 $edst .= "/git/$nr.git";
811                 my $ent;
812                 if ($m) {
813                         $ent = $m->{$key} //
814                                 die("BUG: `$key' not in manifest.js.gz");
815                         if (defined(my $d = $ent->{description})) {
816                                 $d =~ s/ \[epoch [0-9]+\]\z//s;
817                                 $desc = $d;
818                         }
819                 }
820                 if (!$want || $want->{$nr}) {
821                         my $etask = bless { %$task, -key => $key }, __PACKAGE__;
822                         $etask->{-ent} = $ent; # may have {reference}
823                         $etask->{cur_src} = $src;
824                         $etask->{cur_dst} = $edst;
825                         $etask->{-is_epoch} = $fini;
826                         my $ref = $ent->{reference} // '';
827                         push @{$TODO->{$ref}}, $etask;
828                         $self->{any_want}->{$key} = 1;
829                 } else { # create a placeholder so users only need to chmod +w
830                         init_placeholder($src, $edst, $ent);
831                         push @{$task->{-read_only}}, $edst;
832                         push @skip, $key;
833                 }
834         }
835         # filter out the epochs we skipped
836         $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
837
838         (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
839
840         $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
841                 _get_txt_start($task, '_/text/config/raw', $fini);
842
843         defined($desc) ? ($task->{'txt.description'} = $desc) :
844                 _get_txt_start($task, 'description', $fini);
845 }
846
847 sub decode_manifest ($$$) {
848         my ($fh, $fn, $uri) = @_;
849         my $js;
850         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
851         gunzip(\$gz => \$js, MultiStream => 1) or
852                 die "gunzip($uri): $GunzipError\n";
853         my $m = eval { PublicInbox::Config->json->decode($js) };
854         die "$uri: error decoding `$js': $@\n" if $@;
855         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
856         $m;
857 }
858
859 sub load_current_manifest ($) {
860         my ($self) = @_;
861         my $fn = $self->{-manifest} // return;
862         if (open(my $fh, '<', $fn)) {
863                 decode_manifest($fh, $fn, $fn);
864         } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
865                 warn "open($fn): $!\n" if !$self->{-initial_clone};
866                 undef;
867         } else {
868                 die "open($fn): $!\n";
869         }
870 }
871
872 sub multi_inbox ($$$) {
873         my ($self, $path, $m) = @_;
874         my $incl = $self->{lei}->{opt}->{include};
875         my $excl = $self->{lei}->{opt}->{exclude};
876
877         # assuming everything not v2 is v1, for now
878         my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
879         my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
880         my $v2 = {};
881
882         for (@v2_epochs) {
883                 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
884                 push @{$v2->{$1}}, $_;
885         }
886         my $n = scalar(keys %$v2) + scalar(@v1);
887         my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
888         if (defined $incl) {
889                 my $re = '(?:'.join('\\z|', map {
890                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
891                         } @$incl).'\\z)';
892                 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
893                 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
894                 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
895                 @v1 = grep(/$re/, @v1);
896         }
897         if (defined $excl) {
898                 my $re = '(?:'.join('\\z|', map {
899                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
900                         } @$excl).'\\z)';
901                 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
902                 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
903                 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
904                 @v1 = grep(!/$re/, @v1);
905         }
906         my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
907         $ret->{v1} = \@v1 if @v1;
908         $ret->{v2} = $v2 if keys %$v2;
909         $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
910                                 join("\n\t", sort @orig)
911                         : "Nothing available to clone\n";
912         my $path_pfx = '';
913
914         # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
915         if (@v2_epochs) {
916                 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
917                                 @v2_epochs) == @v2_epochs) {
918                         $$path =~ s!\A(/[^/]+)/!/! or last;
919                         $path_pfx .= $1;
920                 }
921         } elsif (@v1) {
922                 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
923                         $path_pfx .= $1;
924                 }
925         }
926         ($path_pfx, $n, $ret);
927 }
928
929 sub clone_all {
930         my ($self, $m) = @_;
931         my $todo = $TODO;
932         $TODO = \'BUG on further use';
933         my $end = PublicInbox::OnDestroy->new($$, \&fgrp_fetch_all, $self);
934         {
935                 my $nodep = delete $todo->{''};
936
937                 # do not download unwanted deps
938                 my $any_want = delete $self->{any_want};
939                 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
940                 my @nodep = delete(@$todo{@unwanted});
941                 push(@$nodep, @$_) for @nodep;
942
943                 # handle no-dependency repos, first
944                 for (@$nodep) {
945                         clone_v1($_, $end);
946                         return if !keep_going($self);
947                 }
948         }
949         # resolve references, deepest, first:
950         while (scalar keys %$todo) {
951                 for my $x (keys %$todo) {
952                         my ($nr, $nxt);
953                         # resolve multi-level references
954                         while ($m && defined($nxt = $m->{$x}->{reference})) {
955                                 exists($todo->{$nxt}) or last;
956                                 die <<EOM if ++$nr > 1000;
957 E: dependency loop detected (`$x' => `$nxt')
958 EOM
959                                 $x = $nxt;
960                         }
961                         my $y = delete $todo->{$x} // next; # already done
962                         for (@$y) {
963                                 clone_v1($_, $end);
964                                 return if !keep_going($self);
965                         }
966                         last; # restart %$todo iteration
967                 }
968         }
969
970         # $end->DESTROY will call fgrp_fetch_all once all references
971         # in $LIVE are gone, and do_reap will eventually drain $LIVE
972         $end = undef;
973         do_reap($self, 1);
974 }
975
976 sub dump_manifest ($$) {
977         my ($m, $ft) = @_;
978         # write the smaller manifest if epochs were skipped so
979         # users won't have to delete manifest if they +w an
980         # epoch they no longer want to skip
981         my $json = PublicInbox::Config->json->encode($m);
982         my $mtime = (stat($ft))[9];
983         seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
984         truncate($ft, 0) or die "truncate($ft): $!";
985         gzip(\$json => $ft) or die "gzip($ft): $GzipError";
986         $ft->flush or die "flush($ft): $!";
987         utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
988 }
989
990 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
991 sub try_manifest {
992         my ($self) = @_;
993         my $uri = URI->new($self->{src});
994         my $lei = $self->{lei};
995         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
996         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
997         my $path = $uri->path;
998         chop($path) eq '/' or die "BUG: $uri not canonicalized";
999         $uri->path($path . '/manifest.js.gz');
1000         my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
1001         my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
1002         if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
1003                 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
1004                 delete $opt{TMPDIR};
1005         }
1006         my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
1007         my $cmd = $curl->for_uri($lei, $uri, qw(-R -o), $ft->filename);
1008         push(@$cmd, '-z', $manifest) if -f $manifest;
1009         my $mf_url = "$uri";
1010         %opt = map { $_ => $lei->{$_} } (0..2);
1011         my $cerr = run_reap($lei, $cmd, \%opt);
1012         if ($cerr) {
1013                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1014                 return $lei->child_error($cerr, "@$cmd failed");
1015         }
1016
1017         # bail out if curl -z/--timecond hit 304 Not Modified, $ft will be empty
1018         return $lei->qerr("# $manifest unchanged") if -f $manifest && !-s $ft;
1019
1020         my $m = eval { decode_manifest($ft, $ft, $uri) };
1021         if ($@) {
1022                 warn $@;
1023                 return try_scrape($self);
1024         }
1025         local $self->{chg} = {};
1026         local $self->{-local_manifest} = load_current_manifest($self);
1027         my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1028         return $lei->child_error(1, $multi) if !ref($multi);
1029         my $v2 = delete $multi->{v2};
1030         if ($v2) {
1031                 for my $name (sort keys %$v2) {
1032                         my $epochs = delete $v2->{$name};
1033                         my %v2_epochs = map {
1034                                 $uri->path($n > 1 ? $path_pfx.$path.$_
1035                                                 : $path_pfx.$_);
1036                                 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1037                                 $e // die "no [0-9]+\.git in `$uri'";
1038                                 $e => [ $uri->clone, $_ ];
1039                         } @$epochs;
1040                         ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1041                                 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1042                         local $self->{cur_src} = $1;
1043                         local $self->{cur_dst} = $self->{dst};
1044                         if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1045                                                         git/[0-9]+\.git\z!x) {
1046                                 $self->{cur_dst} .= "/$1";
1047                         }
1048                         index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1049 E: `$self->{cur_dst}' must not contain newline
1050 EOM
1051                         clone_v2_prep($self, \%v2_epochs, $m);
1052                         return if !keep_going($self);
1053                 }
1054         }
1055         if (my $v1 = delete $multi->{v1}) {
1056                 my $p = $path_pfx.$path;
1057                 chop($p) if substr($p, -1, 1) eq '/';
1058                 $uri->path($p);
1059                 for my $name (@$v1) {
1060                         my $task = bless { %$self }, __PACKAGE__;
1061                         $task->{-ent} = $m->{$name} //
1062                                         die("BUG: no `$name' in manifest");
1063                         $task->{cur_src} = "$uri";
1064                         $task->{cur_dst} = $task->{dst};
1065                         $task->{-key} = $name;
1066                         if ($n > 1) {
1067                                 $task->{cur_dst} .= $name;
1068                                 $task->{cur_src} .= $name;
1069                         }
1070                         index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1071 E: `$task->{cur_dst}' must not contain newline
1072 EOM
1073                         $task->{cur_src} .= '/';
1074                         my $dep = $task->{-ent}->{reference} // '';
1075                         push @{$TODO->{$dep}}, $task; # for clone_all
1076                         $self->{any_want}->{$name} = 1;
1077                 }
1078         }
1079         delete local $lei->{opt}->{epoch} if defined($v2);
1080         clone_all($self, $m);
1081         return if $self->{dry_run} || !keep_going($self);
1082
1083         # set by clone_v2_prep/-I/--exclude
1084         my $mis = delete $self->{chg}->{fp_mismatch};
1085         if ($mis) {
1086                 my $t = (stat($ft))[9];
1087                 $t = strftime('%F %k:%M:%S %z', localtime($t));
1088                 warn <<EOM;
1089 W: Fingerprints for the following repositories do not match
1090 W: $mf_url @ $t:
1091 W: These repositories may have updated since $t:
1092 EOM
1093                 warn "\t", $_, "\n" for @$mis;
1094                 warn <<EOM if !$self->{lei}->{opt}->{prune};
1095 W: The above fingerprints may never match without --prune
1096 EOM
1097         }
1098         dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1099         my $bad = delete $self->{chg}->{badlink};
1100         warn(<<EOM, map { ("\t", $_, "\n") } @$bad) if $bad;
1101 W: The following exist and have not been converted to symlinks
1102 EOM
1103         ft_rename($ft, $manifest, 0666);
1104 }
1105
1106 sub start_clone_url {
1107         my ($self) = @_;
1108         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1109         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1110 }
1111
1112 sub do_mirror { # via wq_io_do or public-inbox-clone
1113         my ($self) = @_;
1114         my $lei = $self->{lei};
1115         $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1116         umask($lei->{client_umask}) if defined $lei->{client_umask};
1117         $self->{-initial_clone} = 1 if !-d $self->{dst};
1118         eval {
1119                 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1120                 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1121 --inbox-config must be one of `always', `v2', `v1', or `never'
1122
1123                 # we support --objstore= and --manifest= with '' (empty string)
1124                 for my $default (qw(objstore manifest.js.gz)) {
1125                         my ($k) = (split(/\./, $default))[0];
1126                         my $v = $lei->{opt}->{$k} // next;
1127                         $v = $default if $v eq '';
1128                         $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1129                         $self->{"-$k"} = $v;
1130                 }
1131                 local $LIVE = {};
1132                 local $TODO = {};
1133                 local $FGRP_TODO = {};
1134                 my $iv = $lei->{opt}->{'inbox-version'} //
1135                         return start_clone_url($self);
1136                 return clone_v1($self) if $iv == 1;
1137                 die "bad --inbox-version=$iv\n" if $iv != 2;
1138                 die <<EOM if $self->{src} !~ m!://!;
1139 cloning local v2 inboxes not supported
1140 EOM
1141                 try_scrape($self, 1);
1142         };
1143         $lei->fail($@) if $@;
1144 }
1145
1146 sub start {
1147         my ($cls, $lei, $src, $dst) = @_;
1148         my $self = bless { src => $src, dst => $dst }, $cls;
1149         $lei->request_umask;
1150         my ($op_c, $ops) = $lei->workers_start($self, 1);
1151         $lei->{wq1} = $self;
1152         $self->wq_io_do('do_mirror', []);
1153         $self->wq_close;
1154         $lei->wait_wq_events($op_c, $ops);
1155 }
1156
1157 sub ipc_atfork_child {
1158         my ($self) = @_;
1159         $self->{lei}->_lei_atfork_child;
1160         $self->SUPER::ipc_atfork_child;
1161 }
1162
1163 sub write_makefile {
1164         my ($dir, $ibx_ver) = @_;
1165         my $f = "$dir/Makefile";
1166         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1167                 print $fh <<EOM or die "print($f) $!";
1168 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1169 # manpage for more information on the format.  This Makefile is
1170 # intended as a familiar wrapper for users unfamiliar with
1171 # public-inbox-* commands.
1172 #
1173 # See the respective manpages for public-inbox-fetch(1),
1174 # public-inbox-index(1), etc for more information on
1175 # some of the commands used by this Makefile.
1176 #
1177 # This Makefile will not be modified nor read by public-inbox,
1178 # so you may edit it freely with your own convenience targets
1179 # and notes.  public-inbox-fetch will recreate it if removed.
1180 EOM
1181                 print $fh <<'EOM' or die "print($f): $!";
1182 # the default target:
1183 help :
1184         @echo Common targets:
1185         @echo '    make fetch        - fetch from remote git repostorie(s)'
1186         @echo '    make update       - fetch and update index '
1187         @echo
1188         @echo Rarely needed targets:
1189         @echo '    make reindex      - may be needed for new features/bugfixes'
1190         @echo '    make compact      - rewrite Xapian storage to save space'
1191         @echo '    make index        - initial index after clone
1192
1193 fetch :
1194         public-inbox-fetch
1195 update :
1196         @if ! public-inbox-fetch --exit-code; \
1197         then \
1198                 c=$$?; \
1199                 test $$c -eq 127 && exit 0; \
1200                 exit $$c; \
1201         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1202         then \
1203                 public-inbox-index; \
1204         else \
1205                 echo 'public-inbox index not initialized'; \
1206                 echo 'see public-inbox-index(1) man page'; \
1207         fi
1208 index :
1209         public-inbox-index
1210 reindex :
1211         public-inbox-index --reindex
1212 compact :
1213         public-inbox-compact
1214
1215 .PHONY : help fetch update index reindex compact
1216 EOM
1217                 close $fh or die "close($f): $!";
1218         } else {
1219                 die "open($f): $!" unless $!{EEXIST};
1220         }
1221 }
1222
1223 1;