aboutsummaryrefslogtreecommitdiffstats
path: root/mailsync.sh
diff options
context:
space:
mode:
Diffstat (limited to 'mailsync.sh')
-rwxr-xr-xmailsync.sh67
1 files changed, 67 insertions, 0 deletions
diff --git a/mailsync.sh b/mailsync.sh
new file mode 100755
index 0000000..1ea2aa2
--- /dev/null
+++ b/mailsync.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+# ~/bin/mailsync.sh
+#
+# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+# Defensive: don't rely on cron/systemd/whatever invokes this to have
+# set these correctly. Explicit beats inferred, especially after the
+# HOME-not-set failure we hit once already. Fall back to the invoking
+# user's home from passwd rather than a hardcoded path.
+export HOME="${HOME:-$(getent passwd "$(id -u)" | cut -d: -f6)}"
+export GNUPGHOME="${GNUPGHOME:-$HOME/.gnupg}"
+
+LOCKFILE="/tmp/mbsync.lock"
+LOGFILE="$HOME/.local/state/mailsync.log"
+MAX_LOG_BYTES=$((10 * 1024 * 1024)) # rotate past 10MB, see note below
+
+exec 200>"$LOCKFILE"
+if ! flock -n 200; then
+ echo "$(date -Iseconds) === SKIPPED: previous run still in progress ===" >> "$LOGFILE"
+ exit 1
+fi
+
+# Simple rotation: if the log's gotten big, keep the last run's worth
+# and move the rest aside rather than letting it grow forever.
+if [ -f "$LOGFILE" ] && [ "$(stat -c%s "$LOGFILE" 2>/dev/null || echo 0)" -gt "$MAX_LOG_BYTES" ]; then
+ mv "$LOGFILE" "${LOGFILE}.1"
+fi
+
+START_TS="$(date -Iseconds)"
+{
+ echo "===== RUN START: $START_TS ====="
+
+ # Timestamp every line of mbsync/notmuch output as it streams,
+ # rather than only marking run boundaries, this is what actually
+ # lets you tell which errors are from which run at a glance.
+ mbsync -a 2>&1 | while IFS= read -r line; do
+ echo "$(date '+%H:%M:%S') $line"
+ done
+ MBSYNC_STATUS=${PIPESTATUS[0]}
+
+ notmuch new 2>&1 | while IFS= read -r line; do
+ echo "$(date '+%H:%M:%S') $line"
+ done
+ NOTMUCH_STATUS=${PIPESTATUS[0]}
+
+ END_TS="$(date -Iseconds)"
+ if [ "$MBSYNC_STATUS" -eq 0 ] && [ "$NOTMUCH_STATUS" -eq 0 ]; then
+ echo "===== RUN END: $END_TS status=OK ====="
+ else
+ echo "===== RUN END: $END_TS status=FAILED mbsync=$MBSYNC_STATUS notmuch=$NOTMUCH_STATUS ====="
+ fi
+} >> "$LOGFILE"
+
+exit 0