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