#!/usr/bin/env bash
#FIXME: Install notmuch mail indexer for mutt NOT TESTED YET

# NB the following macro is already in mutt-wizard.muttrc
#macro index \Cf "<enter-command>unset wait_key<enter><shell-escape>read -p 'Enter a search term to find with notmuch: ' x; echo \$x >~/.cache/mutt_terms<enter><limit>~i \"\`notmuch search --output=messages \$(cat ~/.cache/mutt_terms) | head -n 600 | perl -le '@a=<>;s/\^id:// for@a;$,=\"|\";print@a' | perl -le '@a=<>; chomp@a; s/\\+/\\\\+/ for@a;print@a' \`\"<enter>" "show only messages matching a notmuch pattern"


apt install -y notmuch-mutt notmuch-doc notmuch-vim notmuch-git muchsync notmuch-addrlookup

DEST=${1:-/etc/skel}
NEOMUTTCONF="${DEST}/.config/mutt"
MAILDIR="${DEST}/.local/share/mail"  # set by mutt-wizard setup

mkdir -p ${NEOMUTTCONF}
cat >> ${NEOMUTTCONF}/muttrc <<'EOF'
# notmuch
set nm_default_uri = "notmuch:///$HOME/.local/share/mail"
virtual-mailboxes "My INBOX" "notmuch://?query=tag:inbox"

macro index <F8> \
    "<enter-command>unset wait_key<enter><shell-escape>/usr/bin/notmuch-mutt --prompt search<enter><change-folder-readonly>~/.cache/mutt_results<enter>" \
    "search mail (using notmuch)"

macro index <F9> \
    "<enter-command>unset wait_key<enter><pipe-message>/usr/bin/notmuch-mutt thread<enter><change-folder-readonly>~/.cache/mutt_results<enter><enter-command>set wait_key<enter>" \
    "search and reconstruct owning thread (using notmuch)"


tag-transforms "attachment" "@" \
               "encrypted"  "" \
               "signed"     "✎"

tag-formats "attachment" "GA" \
            "encrypted"  "GE" \
            "signed"     "GS"
EOF

mkdir -p ${MAILDIR}/.notmuch/hooks
cat >  ${MAILDIR}/.notmuch/hooks/post-new.notmuch.example <<EOF
# immediately archive all messages from "me"
notmuch tag -new -- tag:new and from:me@example.com

# delete all messages from a spammer:
notmuch tag +deleted -- tag:new and from:spam@spam.com

# tag all message from notmuch mailing list
notmuch tag +notmuch -- tag:new and to:notmuch@notmuchmail.org

# finally, retag all "new" messages "inbox" and "unread"
notmuch tag +inbox +unread -new -- tag:new
EOF
