+sub _maildir_each_file ($$;@) {
+ my ($dir, $cb, @arg) = @_;
+ for my $d (qw(new/ cur/)) {
+ my $pfx = $dir.$d;
+ opendir my $dh, $pfx or next;
+ while (defined(my $fn = readdir($dh))) {
+ $cb->($pfx.$fn, @arg) if $fn =~ /:2,[A-Za-z]*\z/;
+ }
+ }
+}
+
+sub _augment_file { # _maildir_each_file cb
+ my ($f, $lei) = @_;
+ my $eml = PublicInbox::InboxWritable::eml_from_path($f) or return;
+ _augment($eml, $lei);
+}
+
+# _maildir_each_file callback, \&CORE::unlink doesn't work with it
+sub _unlink { unlink($_[0]) }
+
+sub _buf2maildir {
+ my ($dst, $buf, $oid, $kw) = @_;
+ my $sfx = join('', sort(map { $kw2char{$_} // () } @$kw));
+ my $rand = ''; # chosen by die roll :P
+ my ($tmp, $fh, $final);
+ do {
+ $tmp = $dst.'tmp/'.$rand."oid=$oid";
+ } while (!sysopen($fh, $tmp, O_CREAT|O_EXCL|O_WRONLY) &&
+ $! == EEXIST && ($rand = int(rand 0x7fffffff).','));
+ if (print $fh $$buf and close($fh)) {
+ $dst .= $sfx eq '' ? 'new/' : 'cur/';
+ $rand = '';
+ do {
+ $final = $dst.$rand."oid=$oid:2,$sfx";
+ } while (!link($tmp, $final) && $! == EEXIST &&
+ ($rand = int(rand 0x7fffffff).','));
+ unlink($tmp) or warn "W: failed to unlink $tmp: $!\n";
+ } else {
+ my $err = $!;
+ unlink($tmp);
+ die "Error writing $oid to $dst: $err";
+ }
+}
+
+
+sub _maildir_write_cb ($$) {
+ my ($dst, $lei) = @_;
+ $dst .= '/' unless substr($dst, -1) eq '/';
+ my $dedupe = $lei->{dedupe} = PublicInbox::LeiDedupe->new($lei, $dst);
+ my $jobs = $lei->{opt}->{jobs} // 0;
+ if ($lei->{opt}->{augment}) {
+ if ($dedupe && $dedupe->prepare_dedupe) {
+ require PublicInbox::InboxWritable; # eml_from_path
+ _maildir_each_file($dst, \&_augment_file, $lei);
+ $dedupe->pause_dedupe if $jobs; # are we forking?
+ }
+ } else { # clobber existing Maildir
+ _maildir_each_file($dst, \&_unlink);
+ }
+ for my $x (qw(tmp new cur)) {
+ my $d = $dst.$x;
+ next if -d $d;
+ require File::Path;
+ if (!File::Path::mkpath($d) && !-d $d) {
+ die "failed to mkpath($d): $!\n";
+ }
+ }
+ $dedupe->prepare_dedupe if $dedupe && !$jobs;
+ sub { # for git_to_mail
+ my ($buf, $oid, $kw) = @_;
+ return _buf2maildir($dst, $buf, $oid, $kw) if !$dedupe;
+ my $eml = PublicInbox::Eml->new($$buf); # copy buf
+ return if $dedupe->is_dup($eml, $oid);
+ undef $eml;
+ _buf2maildir($dst, $buf, $oid, $kw);
+ }
+}
+