summary refs log tree commit diff
path: root/bin/hibiki/mailsync
blob: ae96bd0ec91fb0b7fe0b1f2af070c26f41135e46 (plain) (blame)
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
#!/bin/bash

set -e
[ -n "$DEBUG" ] && set -x

#
# mbsync call here:
#
mbsync -c "$HOME/.config/mbsyncrc" primary

#
# notifications-related only from here:
#

MAILDIR_PATTERN=$HOME/Mail/*
new_mail=$(find ${MAILDIR_PATTERN}/*/new/ -type f | wc -l)
old_mail=$(find ${MAILDIR_PATTERN}/*/cur/ -type f | wc -l)

notify() {
	notify-send \
		-i /usr/share/icons/mdi/scalable/email-plus.svg \
		-a mailsync \
		-c audible \
		"$1" "$2"
}

decode() {
	python -c 'import sys;import email.header;print("".join(list(map(lambda s: s[0] if (type(s[0]) == str) else s[0].decode(s[1] or "utf-8"), email.header.decode_header(sys.stdin.readlines()[0])))))'
}

handle_new_msg() {
	msg=$1

	from=$(awk '/^From:/{print $2}' "$msg" | decode)
	subject=$(awk '/^Subject:/{print}' "$msg" | cut -d' ' -f2- | decode)
	to=$(awk '/^To:/{print $2}' "$msg" | decode)

	if [[ "$to" =~ (lists.sr.ht|noreply.github.com) ]]; then
		subject="$to\n$subject"
	fi

	notify "new mail from: $from" "$subject"
}

if [ "$new_mail" -gt 0 ]; then
	new_inbox=$(find ${MAILDIR_PATTERN}/INBOX/new/ -type f)
	if [ -n "$new_inbox" ]; then
		for msg in "${new_inbox[@]}"; do
			handle_new_msg "$msg"
		done
	else
		notify "new mail" "new: $new_mail / old: $old_mail"
	fi
fi