#!/bin/sh

# Search directory branch(es) to find Maildir folders

# Searches all subdirectories of the directory paths given, or the current
# directory if no arguments (just like find(1) does).  Report anything
# that looks like a Maildir, one per line on stdout.
#
# If given the -d switch (must come before all other arguments),
# it will output the names of both "finished" directories that make up the
# Maildir (i.e., both "foo/cur" and "foo/new", not just "foo").



# "cur" and "new" tend to have tons of files and slow things down,
# so we prune those out.  We also prune standard non-mail directories.
prune='-name cur -o -name new -o -name lost+found -o -name .notmuch'

# if we have our one -d switch
if [ "x$1x" = "x-dx" ]; then
	subs=1
	shift
else
	unset subs
fi

# We look for "tmp" to find Maildir folders (see above).
# Pipe through sed to remove:
#   the actual "tmp" subdir    (mail/foo/tmp -> mail/foo)
# shellcheck disable=SC2086
find "$@" \( \( $prune \) -a -prune \) -o \( -name tmp -a -print \) |
	sed -e 's/\/tmp$//' |
	while read -r dir ; do
		# we found tmp - make sure cur and new exist, too
		{ [ -d "$dir/cur" ] && [ -d "$dir/new" ] ; } || continue
		# output based on -d switch
		if [ -n "$subs" ]; then
			echo "$dir/new"
			echo "$dir/cur"
		else
			echo "$dir"
		fi
	done
