-use PublicInbox::ContentHash qw(content_hash git_sha);
-use PublicInbox::Eml;
-use PublicInbox::Hval qw(to_filename);
-
-sub new {
- my ($cls, $lei, $dir) = @_;
- my $self = bless { ale => $lei->ale, -cfg => {} }, $cls;
- if (defined $dir) { # updating existing saved search
- my $f = $self->{'-f'} = "$dir/lei.saved-search";
- -f $f && -r _ or
- return $lei->fail("$f non-existent or unreadable");
- $self->{-cfg} = PublicInbox::Config::git_config_dump($f);
- my $q = $lei->{mset_opt}->{q_raw} = $self->{-cfg}->{'lei.q'} //
- return $lei->fail("lei.q unset in $f");
- my $lse = $lei->{lse} // die 'BUG: {lse} missing';
- $lei->{mset_opt}->{qstr} = ref($q) ?
- $lse->query_argv_to_string($lse->git, $q) :
- $lse->query_approxidate($lse->git, $q);
- } else { # new saved search
- my $saved_dir = $lei->store_path . '/../saved-searches/';
- my (@name) = ($lei->{ovv}->{dst} =~ m{([\w\-\.]+)/*\z});
- push @name, to_filename($lei->{mset_opt}->{qstr});
- $dir = $saved_dir . join('-', @name);
- require File::Path;
- File::Path::make_path($dir); # raises on error
- $self->{'-f'} = "$dir/lei.saved-search";
- my $q = $lei->{mset_opt}->{q_raw};
- if (ref $q) {
- cfg_set($self, '--add', 'lei.q', $_) for @$q;
- } else {
- cfg_set($self, 'lei.q', $q);
+use PublicInbox::ContentHash qw(git_sha);
+use PublicInbox::MID qw(mids_for_index);
+use Digest::SHA qw(sha256_hex);
+our $LOCAL_PFX = qr!\A(?:maildir|mh|mbox.+|mmdf|v2):!i; # TODO: put in LeiToMail?
+
+# move this to PublicInbox::Config if other things use it:
+my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
+sub cquote_val ($) { # cf. git-config(1)
+ my ($val) = @_;
+ $val =~ s/([\n\t\b])/$cquote{$1}/g;
+ $val;
+}
+
+sub ARRAY_FIELDS () { qw(only include exclude) }
+sub BOOL_FIELDS () {
+ qw(external local remote import-remote import-before threads)
+}
+
+sub lss_dir_for ($$;$) {
+ my ($lei, $dstref, $on_fs) = @_;
+ my $pfx;
+ if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
+ require PublicInbox::URIimap;
+ my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
+ $$dstref = $$uri;
+ $pfx = $uri->mailbox;
+ } else {
+ # can't use Cwd::abs_path since dirname($$dstref) may not exist
+ $$dstref = $lei->rel2abs($$dstref);
+ $$dstref =~ tr!/!/!s;
+ $pfx = $$dstref;
+ }
+ ($pfx) = ($pfx =~ m{([^/]+)/*\z}); # basename
+ my $lss_dir = $lei->share_path . '/saved-searches/';
+ my $d = "$lss_dir$pfx-".sha256_hex($$dstref);
+
+ # fall-back to looking up by st_ino + st_dev in case we're in
+ # a symlinked or bind-mounted path
+ if ($on_fs && !-d $d && -e $$dstref) {
+ my @cur = stat(_);
+ my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
+ my ($c, $o, @st);
+ for my $g ("$pfx-*", '*') {
+ my @maybe = glob("$lss_dir$g/lei.saved-search");
+ for my $f (@maybe) {
+ $c = $lei->cfg_dump($f) // next;
+ $o = $c->{'lei.q.output'} // next;
+ $o =~ s!$LOCAL_PFX!! or next;
+ @st = stat($o) or next;
+ next if pack('dd', @st[1,0]) ne $want;
+ $f =~ m!\A(.+?)/[^/]+\z! and return $1;
+ }
+ }
+ }
+ $d;
+}
+
+sub list {
+ my ($lei, $pfx) = @_;
+ my $lss_dir = $lei->share_path.'/saved-searches';
+ return () unless -d $lss_dir;
+ # TODO: persist the cache? Use another format?
+ my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
+ open my $fh, '>', $f or die "open $f: $!";
+ print $fh "[include]\n";
+ for my $p (glob("$lss_dir/*/lei.saved-search")) {
+ print $fh "\tpath = ", cquote_val($p), "\n";
+ }
+ close $fh or die "close $f: $!";
+ my $cfg = $lei->cfg_dump($f);
+ unlink($f);
+ my $out = $cfg ? $cfg->get_all('lei.q.output') : [];
+ map {;
+ s!$LOCAL_PFX!!;
+ $_;
+ } @$out
+}
+
+sub translate_dedupe ($$$) {
+ my ($self, $lei, $dd) = @_;
+ $dd //= 'content';
+ return 1 if $dd eq 'content'; # the default
+ return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
+ $lei->fail("--dedupe=$dd requires --no-save");
+}
+
+sub up { # updating existing saved search via "lei up"
+ my ($cls, $lei, $dst) = @_;
+ my $f;
+ my $self = bless { ale => $lei->ale }, $cls;
+ my $dir = $dst;
+ output2lssdir($self, $lei, \$dir, \$f) or
+ return $lei->fail("--no-save was used with $dst cwd=".
+ $lei->rel2abs('.'));
+ $self->{-cfg} = $lei->cfg_dump($f) // return $lei->fail;
+ $self->{-ovf} = "$dir/over.sqlite3";
+ $self->{'-f'} = $f;
+ $self->{lock_path} = "$self->{-f}.flock";
+ $self;
+}
+
+sub new { # new saved search "lei q --save"
+ my ($cls, $lei) = @_;
+ my $self = bless { ale => $lei->ale }, $cls;
+ require File::Path;
+ my $dst = $lei->{ovv}->{dst};
+
+ # canonicalize away relative paths into the config
+ if ($lei->{ovv}->{fmt} eq 'maildir' &&
+ $dst =~ m!(?:/*|\A)\.\.(?:/*|\z)! && !-d $dst) {
+ File::Path::make_path($dst);
+ $lei->{ovv}->{dst} = $dst = $lei->abs_path($dst);
+ }
+ my $dir = lss_dir_for($lei, \$dst);
+ File::Path::make_path($dir); # raises on error
+ $self->{-cfg} = {};
+ my $f = $self->{'-f'} = "$dir/lei.saved-search";
+ my $dd = $lei->{opt}->{dedupe};
+ translate_dedupe($self, $lei, $dd) or return;
+ open my $fh, '>', $f or return $lei->fail("open $f: $!");
+ my $sq_dst = PublicInbox::Config::squote_maybe($dst);
+ my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
+ if (ref $q) {
+ $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
+ } else {
+ $q = "\tq = ".cquote_val($q);
+ }
+ $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
+ print $fh <<EOM;
+; to refresh with new results, run: lei up $sq_dst
+; `maxuid' and `lastresult' lines are maintained by "lei up" for optimization
+[lei]
+$q
+[lei "q"]
+ output = $dst
+EOM
+ print $fh "\tdedupe = $dd\n" if $dd;
+ for my $k (ARRAY_FIELDS) {
+ my $ary = $lei->{opt}->{$k} // next;
+ for my $x (@$ary) {
+ print $fh "\t$k = ".cquote_val($x)."\n";