#!/bin/sh
MBSYNC=$(pgrep mbsync)
NOTMUCH=$(pgrep notmuch)
if [ -n "$MBSYNC" -o -n "$NOTMUCH" ]; then
    echo "Already running one instance of mbsync or notmuch. Exiting..."
    exit 0
fi

maildir="$HOME/.local/share/mail"

echo "Moving messages tagged as *deleted* to Trash"
notmuch search --format=text0 --output=files tag:deleted | while IFS= read -r -d '' filepath; do
    # Skip if already in Trash
    case "$filepath" in
        */Trash/*)
            continue
            ;;
    esac
    
    # Move to Trash if file exists
    if [ -f "$filepath" ]; then
        filename=$(basename "$filepath")
        mkdir -p "$maildir/Trash/cur"
        mv -v "$filepath" "$maildir/Trash/cur/$filename"
    fi
done

mbsync -Va
notmuch new
PYTHONWARNINGS="ignore::UserWarning" afew --tag --new

# Auto-tag and cleanup
notmuch tag +sent -- folder:Sent and not tag:sent
notmuch tag +trash -- folder:Trash and not tag:trash
notmuch tag -deleted -- folder:Trash
