summaryrefslogtreecommitdiff
path: root/bin/mw
blob: 70a1d3199dcc4d2e947732144bfda83a6f99c826 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/bin/sh
[ ! -f "$HOME/.password-store/.gpg-id" ] && printf "\`pass\` must be installed and initialized to encrypt passwords.\\nBe sure it is installed and run \`pass init <yourgpgemail>\`.\\nIf you don't have a GPG public private key pair, run \`gpg --full-gen-key\` first.\\n" && exit
! command -v mbsync >/dev/null && printf "\`mbsync\` must be installed to run mutt-wizard.\\n" && exit
muttdir="$HOME/.config/mutt"		# Main mutt config location
accdir="$muttdir/accounts"		# Directory for account settings
maildir="$HOME/.local/share/mail"	# Location of mail storage
namere="^[a-z_][a-z0-9_-]*$"		# Regex to ensure viable username
emailre=".\+@.\+\\..\+" 		# Regex to confirm valid email address
muttshare="/usr/share/mutt-wizard"
mbsyncrc="$HOME/.mbsyncrc"
sslcert="/etc/ssl/certs/ca-certificates.crt"
mwconfig="/usr/share/mutt-wizard/mutt-wizard.muttrc"
muttrc="$muttdir/muttrc"

getaccounts() { accounts="$(find "$accdir" -type f | grep -o "[0-9]-.*.muttrc" | sed "s/-/: /g;s/\..*//" | sort -n)" ;}
list() { getaccounts && [ -n "$accounts" ] && echo "$accounts" ;}

getprofiles() { \
	unset msmtp_header msmtp_profile mutt_profile mbsync_profile
	printf "Creating profiles for \`%s\`..." "$title"
msmtp_header="defaults
auth	on
tls	on
tls_trust_file	$sslcert
logfile	~/.config/msmtp/msmtp.log
"
msmtp_profile="
account $title
host $smtp
port $sport
from $fulladdr
user $login
passwordeval \"pass mutt-wizard-$title\""
mbsync_profile="IMAPStore $title-remote
Host $imap
Port  $iport
User $login
PassCmd \"pass mutt-wizard-$title\"
SSLType IMAPS
CertificateFile /etc/ssl/certs/ca-certificates.crt

MaildirStore $title-local
Subfolders Verbatim
Path ~/.local/share/mail/$title/
Inbox ~/.local/share/mail/$title/INBOX
Flatten .

Channel $title
Expunge Both
Master :$title-remote:
Slave :$title-local:
Patterns * !\"[Gmail]/All Mail\"
Create Both
SyncState *
# End profile
"

if [ "$accounttype" = "offline" ]; then
mutt_profile="# vim: filetype=neomuttrc
# muttrc file for account $title
set realname = \"$realname\"
set from = \"$fulladdr\"
set sendmail = \"/usr/bin/msmtp -a $title\"
alias me $realname <$fulladdr>
set folder = \"$maildir/$title\"
set header_cache = $accdir/$title/cache/headers
set message_cachedir = $accdir/$title/cache/bodies
set certificate_file = $accdir/$title/certificates
set mbox_type = Maildir

bind index,pager gg noop
bind index,pager g noop
bind index,pager M noop
bind index,pager C noop
bind index gg first-entry
macro index o \"<shell-escape>mailsync -V $title<enter>\" \"run mbsync to sync $title\"
unmailboxes *
"
else
mutt_profile="# vim: filetype=neomuttrc
# muttrc file for account $title
set realname = \"$realname\"
set from = \"$fulladdr\"
set sendmail = \"/usr/bin/msmtp -a $title\"
alias me $realname <$fulladdr>
set folder = \"imaps://$fulladdr@$imap:$iport\"
set imap_user = \"$login\"
set header_cache = $accdir/$title/cache/headers
set message_cachedir = $accdir/$title/cache/bodies
set certificate_file = $accdir/$title/certificates
set imap_pass = \`pass mutt-wizard-$title\`

set mbox_type = Maildir
set ssl_starttls = yes
set ssl_force_tls = yes

bind index,pager gg noop
bind index,pager g noop
bind index,pager M noop
bind index,pager C noop
bind index gg first-entry
unmailboxes *
"
fi
	printf "DONE.\\n"
}

askinfo() { \
	printf "Insert the \033[31memail address\033[0m that you want to autoconfigure for mutt/mbsync\\n\tEmail: \033[36m"
	read -r fulladdr
	printf "\033[0m"
	while ! echo "$fulladdr" | grep "$emailre" >/dev/null; do
		printf "That is not a valid \033[31memail address\033[0m, please retype the desired email.\\n\\nEmail: \033[36m\t"
		read -r fulladdr
		printf "\033[0m"
	done
	domain="$(echo "$fulladdr" | sed "s/.*@//")"
	printf "\\nSearching for \033[32m%s\033[0m in \033[34m\`domains.csv\`\033[0m..." "$domain"
	serverinfo="$(grep "$domain" "$muttshare/domains.csv" 2>/dev/null)"
	if [ -z "$serverinfo" ]; then
		printf "Your email domain is not in mutt-wizard's database yet.\\nmutt-wizard will still autoconfigure everything, but you will have to manually type in your service's IMAP and SMTP server information.\\nYou can usually quickly find this by internet searching for it.\\n"
		printf "Insert the IMAP server for your email provider (excluding the port number)\\n\033[36m\t"
		read -r imap
		printf "\033[0mWhat is your server's IMAP port number? (Usually something like 993)\\n\033[36m\t"
		read -r iport
		printf "\033[0mInsert the SMTP server for your email provider (excluding the port number)\\n\033[36m\t"
		read -r smtp
		printf "\033[0mWhat is your server's SMTP port number? (Usually 587 or 465)\\n\033[36m\t"
		read -r sport
		printf "\033[0m\\nGreat! If you want to be helpful, copy the line below and you can add it to the \`domains.csv\` file on Github.\\nThis will make things easier for others who use your email provider.\\n\\n%s,%s,%s,%s,%s\\n\\nAlthough be sure to test to see if these settings work first! ;-)\\n" "$domain" "$imap" "$iport" "$smtp" "$sport"
	else
		IFS=, read -r service imap iport smtp sport <<EOF
$serverinfo
EOF
	printf "\\n\033[3;33mCongrats!\033[0m Server info has automatically be found, so you won't have to look anything up!\\n\t\033[1mIMAP server\033[0m: %s\\n\t\033[1mIMAP port\033[0m: %s\\n\t\033[1mSMTP server\033[0m: %s\\n\t\033[1mSMTP port\033[0m: %s\\nThis data will be used by the wizard.\\n" "$imap" "$iport" "$smtp" "$sport"
	case "$service" in
		gmail.com) printf "\033[31mREMEMBER: Gmail users must enable \"less secure\" (third-party) applications first for the sync to work:\\nhttps://support.google.com/accounts/answer/6010255\\n\033[0m" ;;
		protonmail.*) printf "\033[31mREMEMBER: Protonmail users must install and configure Protonmail Bridge first for the sync to work:\\nhttps://protonmail.com/bridge/\\n\033[0m" ;;
	esac
	fi
	printf "Enter the \033[35mfull name\033[0m you want to be identified by on this account.\\n\tReal name: "
	read -r realname
	printf "Enter a short, \033[36mone-word identifier\033[0m for this email account that will distinguish them from any other accounts you add.\\n\tAccount name: "
	read -r title
	while ! echo "$title" | grep "$namere" >/dev/null || ls "$accdir"/[0-9]"-$title.muttrc" >/dev/null 2>&1; do
		printf "\033[31mTry again\033[0m. Pick a nickname that is one word only including lowercase letters and _ or - and that you have \033[1mnot\033[0m used before.\\n\tAccount name: \033[36m\t"
		read -r title
		printf "\033[0m"
	done
	printf "If your account has a special username different from your address, insert it now. Otherwise leave this prompt totally blank.\\n\033[34mMost accounts will not have a separate login, so you should probably leave this blank.\033[0m\\n\tLogin(?): \033[36m"
	read -r login
	printf "\033[0m"
	[ -z "$login" ] && login="$fulladdr"
	getaccounts
	for x in $(seq 1 9); do echo "$accounts" | grep "$x" || { export idnum="$x"; break ;}; done
	getpass
	getprofiles
	mkdir -p "$accdir/$title/cache/bodies" "$HOME/.config/msmtp"
	[ ! -f "$HOME/.config/msmtp/config" ] && echo "$msmtp_header" > "$HOME/.config/msmtp/config"
	echo "$msmtp_profile" >> "$HOME/.config/msmtp/config"
	echo "$mutt_profile" > "$accdir/$idnum-$title.muttrc"
	echo "$mbsync_profile" >> "$mbsyncrc"
	! grep "^source.*.muttrc" "$muttrc" | grep -v "$mwconfig" >/dev/null && echo "source $accdir/$idnum-$title.muttrc # mw-autogenerated" >> "$muttrc"
	echo "macro index,pager i$idnum '<sync-mailbox><enter-command>source $accdir/$idnum-$title.muttrc<enter><change-folder>!<enter>;<check-stats>' \"switch to $fulladdr\" # mw-autogenerated" >> "$muttrc"
}

getpass() { while : ; do pass rm -f "mutt-wizard-$title" >/dev/null 2>&1
		pass insert "mutt-wizard-$title" && break; done ;}

formatShortcut() { \
	while read -r data; do { echo "macro index,pager g$1 \"<change-folder>$data<enter>\" \"go to $2\" # mw-autogenerated"
	echo "macro index,pager M$1 \"<save-message>$data<enter>\" \"move mail to $2\" # mw-autogenerated"
	echo "macro index,pager C$1 \"<copy-message>$data<enter>\" \"copy mail to $2\" # mw-autogenerated"; } >> "$accdir/$idnum-$title.muttrc"
	done ;}

tryconnect() { mkdir -p "$maildir/$title"
	if mailboxes="$(mbsync -l "$title" | sed 's/\//./')" >/dev/null 2>&1; then
		[ "$accounttype" = "online" ] && sed -i "/IMAPStore $title-remote$/,/# End profile/d" "$mbsyncrc"
		printf "\033[32mMailboxes detected.\033[0m\\n"
		echo "$mailboxes" | xargs -I {} mkdir -p "$maildir/$title/{}"
	else
		printf "\033[31m\033[31mLog-on not successful.\033[0m\\nIt seems that either you inputted the wrong password or sever settings, or there are other requirements for your account out of the control of mutt-wizard.\\n"
		return 1
	fi ;}

finalize() { \
	boxes="$(du -a "$maildir/$title/"* -d 0 | sed "s/^.*\//=/")"
	[ -z "$boxes" ] && printf "\033[31mNo local mailboxes have been detected for %s.\033[0m\\nThis means that mbsync has not been successfully run.\\nRun mbsync, and if it has an error, be sure to check your password and server settings manually if needbe.\\n" "$title" && return
	printf "Setting up the mutt sidebar...\\n"
	sidebar_width="$(sed -n -e '/^set sidebar_width/p' "$muttdir/muttrc" | awk -F'=' '{print $2}')"
	delim="$(head -c "$sidebar_width" < /dev/zero | tr '\0' =)"
	printf "Setting default mailboxes for your Inbox, Sent, Drafts and Trash in mutt...\\n"
	oneline="=$title $delim $(echo "$boxes" | sed -e "s/^\|$/\"/g" | tr "\n" " ")"
	spoolfile=$(echo "$boxes" | grep -i -m 1 inbox | sed 's/=/+/g')
	record=$(echo "$boxes" | grep -i -m 1 sent | sed 's/=/+/g')
	postponed=$(echo "$boxes" | grep -i -m 1 draft | sed 's/=/+/g')
	trash=$(echo "$boxes" | grep -i -m 1 trash | sed 's/=/+/g')
	sed -i "/^mailboxes\|^set record\|^set postponed\|^set trash\|^set spoolfile/d" "$accdir/$idnum-$title.muttrc"
	{ echo "set spoolfile = \"$spoolfile\""; echo "set record = \"$record\""; echo "set postponed = \"$postponed\""; echo "set trash = \"$trash\""; } >> "$accdir/$idnum-$title.muttrc"
	echo mailboxes "$oneline" >> "$accdir/$idnum-$title.muttrc"
	printf "Setting up your keyboard shortcuts for jumping between mailboxes...\\n"
	sed -i "/# mw-autogenerated/d" "$accdir/$idnum-$title.muttrc"
	echo "$boxes" | grep -i -m 1 inbox | formatShortcut i inbox
	echo "$boxes" | grep -i -m 1 sent | formatShortcut s sent
	echo "$boxes" | grep -i -m 1 draft | formatShortcut d drafts
	echo "$boxes" | grep -i -m 1 trash | formatShortcut t trash
	echo "$boxes" | grep -i -m 1 spam | formatShortcut S spam
	echo "$boxes" | grep -i -m 1 junk | formatShortcut j junk
	echo "$boxes" | grep -i -m 1 archive | formatShortcut a archive
	[ "$accounttype" = "offline" ] && printf "All done.\\n\033[33mYou should now be able to run \`\033[32mmbsync %s\033[33m\` to begin to download your mail.\033[0m\\n" "$title"
}

confirm() { printf "Do you want to to %s? [y/N]\\n\t" "$@" && read -r input && ! echo "$input" | grep -i "^y$\|^yes$" >/dev/null && printf "That doesn't seem like a yes to me.\\n\\n" && return 1
	printf "Are you really, really sure you want to %s?\\n\t" "$@" && read -r input && ! echo "$input" | grep -i "^y$\|^yes$" >/dev/null && printf "That doesn't seem like a yes to me.\\n\\n" && return 1
	return 0 ;}

pick() { printf "Select an accounts to %s:\\n" "$1"
	list
	read -r input
	[ -z "$input" ] && return 1
	title="$(echo "$accounts" | grep "$input" | awk '{print $2}')"
	[ -z "$title" ] && printf "Invalid response." && return 1
	return 0 ;}

delete() { sed -i "/IMAPStore $title-remote$/,/# End profile/d" "$mbsyncrc"
	rm -rf "${accdir:?}/${title:?}" "$accdir/[1-9]-$title.muttrc"
	sed -i "/[0-9]-$title.muttrc/d" "$muttrc"
	sed -i "/account $title/,/^\(\s*$\|account\)/d" "$HOME/.config/msmtp/config"
	}

choosecron() { ! pgrep crond >/dev/null && echo "No cron manager running. Install/enable one and then select this option again." && return 1
	if crontab -l | grep mailsync >/dev/null; then
		echo "Active mail sync cronjob detected. Do you want to remove it?"
		printf "\033[36m\t"
		read -r rmyn
		printf "\033[0m"
		echo "$rmyn" | grep -i "^y\(es\)*$" >/dev/null && crontab -l | sed '/mailsync/d' | crontab - >/dev/null && echo "Mail sync turned off."
	else
		echo "How many minutes between each mail sync?"
		printf "\033[36m\t"
		read -r minnum
		printf "\033[0m"
		while ! echo "$minnum" | grep "^[0-9]\+$" >/dev/null; do
			printf "That doesn't look like a number. How many minutes between each mail sync?\\n\033[36m\t"
			read -r minnum
			printf "\033[0m"
		done
		(crontab -l; echo "*/$minnum * * * * export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus; export DISPLAY=:0; . \$HOME/.profile; $(type mailsync | cut -d' ' -f3)") | crontab - &&
			echo "Cronjob added. Mail will sync every $minnum minutes. Be sure you have your cron manager running."
	fi ;}

asktype() { while : ; do
		printf "Do you want to keep your mail for this account offline with mbsync? [yes/no]\\n\t"
		read -r offnot
		case "$offnot" in
			[Yy][Ee][Ss]) accounttype="offline" && break ;;
			[Nn][Oo]) accounttype="online" && break ;;
			*) echo "Write out either yes or no completely. Try again or press ctrl-c to quit." ;;
		esac; done ;}

init() { mkdir -p "$muttdir" "$accdir"
	[ ! -f "$muttrc" ] && echo "# vim: filetype=neomuttrc" > "$muttrc" && echo "muttrc created."
	! grep "^source.*mutt-wizard.muttrc" "$muttrc" >/dev/null && echo "source $mwconfig # mw-autogenerated" >> "$muttrc" && echo "muttrc will now source mutt-wizard."
}

purge() { confirm "delete all account data" || exit
	rm -rf "$mbsyncrc" "$accdir" "$HOME/.config/msmtp"
	echo "All configs and account settings have been purged."
	sed -i "/\# mw-autogenerated/d" "$muttrc"
}

case "$1" in
	init) init ;;
	ls) list ;;
	add) asktype && askinfo && tryconnect && finalize || delete ;;
	pass) pick "change the password of" && getpass ;;
	delete) pick delete && confirm "delete the \`$title\` profile" && delete ;;
	purge) purge ;;
	cron) choosecron ;;
	*) cat << EOF
mw: mutt-wizard, auto-configure email accounts for mutt
including downloadable mail with \`isync\`.

Allowed options:
  init		Run once and first to copy required files
  add		Add and autoconfigure an email address (9 max.)
  ls		List configured accounts
  delete	Pick an account to delete
  purge		Delete all accounts and settings
  cron		Enable or disable an autosync via cronjob
  all else	Print this message

NOTE: Once at least one account is added, you can run
\`mbsync -a\` to begin downloading mail.
EOF
esac