aboutsummaryrefslogtreecommitdiffstats
path: root/modules/communication/neomutt/neomutt-sync-daemon.sh
blob: d5eea63f973a983f850f8548e0c01567a90d0f83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env bash
# systemd daemon: sync quick groups on first run, then full groups every 5
# minutes while neomutt is open. Started/stopped by the wrapped neomutt
# launcher.

set -uo pipefail

# Comma-separated group names, substituted at build time
QUICK_GROUPS="@@QUICK_GROUPS@@"
FULL_GROUPS="@@FULL_GROUPS@@"

INTERVAL="$((5 * 60))"

IFS=',' read -ra QUICK <<<"$QUICK_GROUPS"
IFS=',' read -ra FULL <<<"$FULL_GROUPS"

# sync_groups <group>...: sync the given mbsync groups, then index
sync_groups() {
  if (($# == 0)); then
    return 0
  fi

  echo "Syncing: $*"
  mbsync "$@"
  local status=$?
  if ((status != 0)); then
    echo "mbsync failed (status $status) for: $*" >&2
    return "$status"
  fi

  echo "Indexing new mail with notmuch..."
  notmuch new
}

first=true

while true; do
  if $first; then
    # Quick pass first so new mail shows up before the slower full sync
    sync_groups "${QUICK[@]}"
    first=false
  fi

  sync_groups "${FULL[@]}"

  # Safety net: the launcher stops this service when neomutt exits; if that
  # didn't happen (hard kill), bail out once neomutt is gone.
  if ! pgrep -x neomutt-launche >/dev/null; then
    echo "neomutt is not running; stopping sync daemon" >&2
    exit 0
  fi

  # Sleep after syncing and trying to exit, this makes sure that it runs once
  # after all neomutt instances closes
  sleep "$INTERVAL"
done