#!/usr/bin/env sh VERBOSE= if [ "$1" = "-v" ]; then VERBOSE=1 shift fi mbsync_running() { account_escaped=$(printf '%s\n' "$1" | sed 's/[.[\*^$()+?{|\\]/\\&/g') pgrep -f "^mbsync([[:space:]]+[^ ]+)*[[:space:]]+$account_escaped($|[[:space:]])" >/dev/null || pgrep -f "^mbsync([[:space:]]+[^ ]+)*[[:space:]]+-a($|[[:space:]])" >/dev/null } # Run only if not already running in other instance if mbsync_running "$1"; then _acc="$([ -z "$1" ] && echo "all" || echo "$1")" echo "mbsync ($_acc) is already running." exit fi notify() { notify-send --app-name="Mail" -- "$1" "$2" } MAILDIR="$XDG_DATA_HOME/mail" lastrun_base="$XDG_CACHE_HOME/.mailsynclastrun" lastrun="$lastrun_base" [ -n "$1" ] && { lastrun="${lastrun}_$1" } time_lastrun="$(stat -c %Y "$lastrun" 2>/dev/null || echo '0')" [ -f "$lastrun_base" ] || touch "$lastrun_base" [ -f "$lastrun" ] || touch "$lastrun" rm_flag= mbsync_flag="-q" notmuch_flag="--quiet" if [ -n "$VERBOSE" ]; then rm_flag="-v" mbsync_flag="--verbose" notmuch_flag="--verbose" fi # delete all +deleted messages notmuch search --format=text0 --output=files tag:deleted | xargs -0 --no-run-if-empty rm $rm_flag sync_and_notify() { mbsync $mbsync_flag "$1" new=$(fd --type f --changed-after "@$time_lastrun" . "$MAILDIR/$1/INBOX/new/" "$MAILDIR/$1/INBOX/cur/" 2>/dev/null) newcount=$(echo "$new" | sed '/^\s*$/d' | wc -l) case 1 in $((newcount > 5))) echo "$newcount new mail for $1." notify "New Mail!" "$newcount new mail(s)." ;; $((newcount > 0))) echo "$newcount new mail for $1." for file in $new; do # Extract and decode subject and sender from mail. subject=$(awk '/^Subject: / && ++n == 1,/^.*: / && ++i == 2' "$file" | head -n-1 | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | sed 's/^Subject: //' | tr -d '\n\t') from="$(sed -n "/^From:/ s|From: *|| p" "$file" | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)')" from="${from% *}" from="${from%\"}" from="${from#\"}" notify "$from:" "$subject" done ;; *) echo "No new mail for $1." ;; esac } allaccounts="$(grep -hs "^\(Group\)" "$XDG_CONFIG_HOME/isyncrc")" IFS=' ' if [ -z "$1" ]; then tosync="$allaccounts" else tosync="$(for arg in "$@"; do for availacc in $allaccounts; do [ "$arg" = "${availacc##* }" ] && echo "$availacc" && break done || echo "error $arg"; done)" fi for account in $tosync; do case $account in Group*) sync_and_notify "${account##* }" & ;; error*) echo "ERROR: Account ${account##* } not found." ;; esac done wait if pgrep -f 'notmuch new' >/dev/null; then notify "Notmuch running" "Notmuch new is running from another sync.\n Please run it again later." else notmuch new $notmuch_flag fi #Create a touch file that indicates the time of the last run of mailsync if [ -z "$1" ]; then # if no args are provided, touch all files touch "${lastrun_base}"* else touch "$lastrun" fi