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