You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

396 lines
14 KiB

  1. #!/bin/sh
  2. command -V gpg >/dev/null 2>&1 && GPG="gpg" || GPG="gpg2"
  3. [ -z ${PASSWORD_STORE_DIR+x} ] && PASSWORD_STORE_DIR="$HOME/.password-store"
  4. [ -r "$PASSWORD_STORE_DIR/.gpg-id" ] &&
  5. "$GPG" --list-secret-keys $(cat "$PASSWORD_STORE_DIR/.gpg-id") >/dev/null 2>&1 || {
  6. 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 \`%s --full-gen-key\` first.\\n" "$GPG"
  7. exit 1
  8. }
  9. prefix="/usr/local"
  10. pass_prefix="mw-"
  11. muttdir="${XDG_CONFIG_HOME:-$HOME/.config}/mutt" # Main mutt config location
  12. accdir="$muttdir/accounts" # Directory for account settings
  13. maildir="${XDG_DATA_HOME:-$HOME/.local/share}/mail" # Location of mail storage
  14. emailre=".+@.+\..+" # Regex to confirm valid email address
  15. muttshare="$prefix/share/mutt-wizard"
  16. mbsyncrc="${MBSYNCRC:-$HOME/.mbsyncrc}"
  17. mwconfig="$muttshare/mutt-wizard.muttrc"
  18. cachedir="${XDG_CACHE_HOME:-$HOME/.cache}/mutt-wizard"
  19. muttrc="$muttdir/muttrc"
  20. msmtprc="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/config"
  21. msmtplog="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/msmtp.log"
  22. marker="# mw-autogenerated"
  23. imap_h_delim='.'
  24. alias mbsync='mbsync -c "$mbsyncrc"'
  25. for x in "/etc/ssl/certs/ca-certificates.crt" "/etc/pki/tls/certs/ca-bundle.crt" "/etc/ssl/ca-bundle.pem" "/etc/pki/tls/cacert.pem" "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" "/etc/ssl/cert.pem" "/usr/local/share/ca-certificates/"
  26. do
  27. [ -f "$x" ] && sslcert="$x" && break
  28. done || { echo "CA Certificate not found. Please install one or link it to /etc/ssl/certs/ca-certificates.crt" && exit 1 ;}
  29. getaccounts() { accounts="$(find -L "$accdir" -type f | grep -o "[0-9]-.*.muttrc" | sed "s/-/: /;s/\.muttrc$//" | sort -n)" ;}
  30. list() { getaccounts && [ -n "$accounts" ] && echo "$accounts" ;}
  31. updihdelim() {
  32. if command -V curl >/dev/null 2>&1 && command -V sed >/dev/null 2>&1 ; then
  33. imap_h_delim="$(printf -- '-u %s:%s\n' "$login" "$(pass "$pass_prefix$fulladdr")" |\
  34. curl -s -k --url "imaps://$imap" -K- --request 'LIST "" ""' |\
  35. sed -n 's/\* LIST (\\Noselect) "\(.*\)" ""/\1/p')"
  36. fi
  37. if [ -z "${imap_h_delim}" ] || [ "${imap_h_delim}" = '\' ] || [ "${imap_h_delim}" = '/' ]; then
  38. printf '%s\n' 'Defaulting IMAP hierarchy delimiter to "."'
  39. imap_h_delim='.'
  40. fi
  41. }
  42. getprofiles() { \
  43. unset msmtp_header msmtp_profile mutt_profile mbsync_profile
  44. [ "$iport" = "1143" ] && imapssl="None"
  45. # Determine IMAP hierarchy delimiter
  46. updihdelim
  47. msmtp_header="defaults
  48. auth on
  49. tls on
  50. tls_trust_file $sslcert
  51. logfile $msmtplog
  52. "
  53. msmtp_profile="account $fulladdr
  54. host $smtp
  55. port ${sport:-587}
  56. from $fulladdr
  57. user $login
  58. passwordeval \"pass $pass_prefix$fulladdr\"
  59. $tlsline
  60. "
  61. mbsync_profile="IMAPStore $fulladdr-remote
  62. Host $imap
  63. Port ${iport:-993}
  64. User $login
  65. PassCmd \"pass $pass_prefix$fulladdr\"
  66. AuthMechs LOGIN
  67. SSLType ${imapssl:-IMAPS}
  68. CertificateFile $sslcert
  69. MaildirStore $fulladdr-local
  70. Subfolders Verbatim
  71. Path ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$fulladdr/
  72. Inbox ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$fulladdr/INBOX
  73. Flatten ${imap_h_delim}
  74. Channel $fulladdr
  75. Expunge Both
  76. Master :$fulladdr-remote:
  77. Slave :$fulladdr-local:
  78. Patterns * !\"[Gmail]/All Mail\"
  79. Create Both
  80. SyncState *
  81. MaxMessages ${maxmes:-0}
  82. ExpireUnread no
  83. # End profile
  84. "
  85. if [ -z "${online+x}" ]; then
  86. mutt_profile="# vim: filetype=neomuttrc
  87. # muttrc file for account $fulladdr
  88. set realname = \"$realname\"
  89. set from = \"$fulladdr\"
  90. set sendmail = \"msmtp -a $fulladdr\"
  91. alias me $realname <$fulladdr>
  92. set folder = \"$maildir/$fulladdr\"
  93. set header_cache = $cachedir/$fulladdr/headers
  94. set message_cachedir = $cachedir/$fulladdr/bodies
  95. set mbox_type = Maildir
  96. set sidebar_delim_chars = '/${imap_h_delim}'
  97. bind index,pager gg noop
  98. bind index,pager g noop
  99. bind index,pager M noop
  100. bind index,pager C noop
  101. bind index gg first-entry
  102. macro index o \"<shell-escape>mw -y $fulladdr<enter>\" \"run mbsync to sync $fulladdr\"
  103. unmailboxes *
  104. unalternates *
  105. "
  106. else
  107. mutt_profile="# vim: filetype=neomuttrc
  108. # muttrc file for account $fulladdr
  109. set realname = \"$realname\"
  110. set from = \"$fulladdr\"
  111. set sendmail = \"msmtp -a $fulladdr\"
  112. alias me $realname <$fulladdr>
  113. set folder = \"imaps://$login@$imap:${iport:-993}\"
  114. set imap_user = \"$login\"
  115. set header_cache = $cachedir/$fulladdr/headers
  116. set message_cachedir = $cachedir/$fulladdr/bodies
  117. set imap_pass = \"\`pass $pass_prefix$fulladdr\`\"
  118. set mbox_type = Maildir
  119. set ssl_starttls = yes
  120. set ssl_force_tls = yes
  121. set sidebar_delim_chars = '/${imap_h_delim}'
  122. bind index,pager gg noop
  123. bind index,pager g noop
  124. bind index,pager M noop
  125. bind index,pager C noop
  126. bind index gg first-entry
  127. unmailboxes *
  128. "
  129. fi
  130. }
  131. parsedomains(){ serverinfo="$(grep "^${fulladdr#*@}" "$muttshare/domains.csv" 2>/dev/null)"
  132. [ -z "$serverinfo" ] && serverinfo="$(grep "$(echo "${fulladdr#*@}" | sed "s/\.[^\.]*$/\.\\\*/")" "$muttshare/domains.csv" 2>/dev/null)"
  133. IFS=, read -r service imapsugg iportsugg smtpsugg sportsugg <<EOF
  134. $serverinfo
  135. EOF
  136. imap="${imap:-$imapsugg}"
  137. smtp="${smtp:-$smtpsugg}"
  138. sport="${sport:-$sportsugg}"
  139. iport="${iport:-$iportsugg}"
  140. }
  141. delete() { if [ -z "${fulladdr+x}" ]; then
  142. echo "Select the account your would like to delete (by number):"
  143. list
  144. read -r input
  145. match="^$input:"
  146. else
  147. match=" $fulladdr$"
  148. getaccounts
  149. fi
  150. fulladdr="$(echo "$accounts" | grep "$match" | cut -f2 -d' ')"
  151. [ -z "$fulladdr" ] && echo "Invalid account name given." && return 1
  152. sed -ibu "/IMAPStore $fulladdr-remote$/,/# End profile/d" "$mbsyncrc" ; rm -f "$mbsyncrc"bu
  153. rm -rf "${cachedir:?}/${fulladdr:?}" "$accdir/"[1-9]"-$fulladdr.muttrc"
  154. sed -ibu "/[0-9]-$fulladdr.muttrc/d" "$muttrc" ; rm -f "$muttrc"bu
  155. sed -ibu "/account $fulladdr/,/^\(\s*$\|account\)/d" "$msmtprc"; rm -f "$msmtprc"bu
  156. pass rm -f "$pass_prefix$fulladdr" >/dev/null 2>&1
  157. }
  158. askinfo() { \
  159. [ -z "$fulladdr" ] && echo "Give the full email address to add:" &&
  160. read -r fulladdr
  161. while ! echo "$fulladdr" | grep -qE "$emailre"; do
  162. echo "\`$fulladdr\` is not a valid email address. Please retype the address:"
  163. read -r fulladdr
  164. done
  165. grep -q "Channel\s*$fulladdr$" "$mbsyncrc" &&
  166. { echo "$fulladdr has already been added" && exit 1 ;}
  167. { [ -z "$imap" ] || [ -z "$smtp" ] ;} && parsedomains
  168. [ -z "$imap" ] && echo "Give your email server's IMAP address (excluding the port number):" &&
  169. read -r imap
  170. [ -z "$smtp" ] && echo "Give your email server's SMTP address (excluding the port number):" &&
  171. read -r smtp
  172. [ "$sport" = 465 ] && tlsline="tls_starttls off"
  173. [ -z "$realname" ] && echo "Give the name you would like to be identified by on the email account:" &&
  174. read -r realname
  175. login="${login:-$fulladdr}"
  176. if [ -n "${password+x}" ]; then
  177. createpass
  178. else
  179. getpass
  180. fi
  181. }
  182. createpass() { echo "$password" > "$PASSWORD_STORE_DIR/$pass_prefix$fulladdr"
  183. "$GPG" -qer "$(cat "$PASSWORD_STORE_DIR/.gpg-id")" "$PASSWORD_STORE_DIR/$pass_prefix$fulladdr"
  184. rm -f "$PASSWORD_STORE_DIR/$pass_prefix$fulladdr" ;}
  185. writeinfo() { mkdir -p "$muttdir" "$accdir" "$cachedir/$fulladdr/bodies" "${XDG_CONFIG_HOME:-$HOME/.config}/msmtp" "$maildir/$fulladdr"
  186. # Get accounts and find the first missing account number (max. 9).
  187. getaccounts; for x in $(seq 1 9); do echo "$accounts" | grep -q "$x" || { export idnum="$x"; break ;}; done
  188. # Configure msmtprc for sending mail.
  189. [ ! -f "$msmtprc" ] && echo "$msmtp_header" > "$msmtprc"
  190. echo "$msmtp_profile" >> "$msmtprc"
  191. # On Ubuntu/Debian, a link is needed since they use an older version.
  192. command -V apt-get >/dev/null 2>&1 && ln -s "$msmtprc" "$HOME/.msmtprc" 2>/dev/null
  193. # Create the mbsync config file.
  194. mkdir -p "${mbsyncrc%/*}"
  195. echo "$mbsync_profile" >> "$mbsyncrc"
  196. # Create a muttrc for viewing mail.
  197. echo "$mutt_profile" > "$accdir/$idnum-$fulladdr.muttrc"
  198. [ ! -f "$muttrc" ] && echo "# vim: filetype=neomuttrc" > "$muttrc"
  199. ! grep -q "^source.*mutt-wizard.muttrc" "$muttrc" && echo "source $mwconfig $marker" >> "$muttrc"
  200. ! grep "^source.*.muttrc" "$muttrc" | grep -qv "$mwconfig" && echo "source $accdir/$idnum-$fulladdr.muttrc $marker" >> "$muttrc"
  201. echo "macro index,pager i$idnum '<sync-mailbox><enter-command>source $accdir/$idnum-$fulladdr.muttrc<enter><change-folder>!<enter>;<check-stats>' \"switch to $fulladdr\" $marker" >> "$muttrc"
  202. notmuchauto # Create a notmuch config file if not present already.
  203. }
  204. getpass() { while : ; do pass rm -f "$pass_prefix$fulladdr" >/dev/null 2>&1
  205. pass insert "$pass_prefix$fulladdr" && break; done ;}
  206. formatShortcut() { toappend="$toappend
  207. macro index,pager g$1 \"<change-folder>=$3<enter>\" \"go to $2\" $marker
  208. macro index,pager M$1 \";<save-message>=$3<enter>\" \"move mail to $2\" $marker
  209. macro index,pager C$1 \";<copy-message>=$3<enter>\" \"copy mail to $2\" $marker" >> "$accdir/$idnum-$fulladdr.muttrc" ;}
  210. setBox() { toappend="$toappend
  211. set $1 = \"+$2\" $marker" ;}
  212. getboxes() { [ -n "${force+x}" ] && mailboxes="INBOX
  213. Drafts
  214. Junk
  215. Trash
  216. Sent
  217. Archive" && return 0
  218. if mailboxes="$(mbsync -l "$fulladdr" | sed "s/\//${imap_h_delim}/")" >/dev/null 2>&1 && [ -n "$mailboxes" ]; then
  219. [ -n "${online+x}" ] && sed -ibu "/IMAPStore $fulladdr-remote$/,/# End profile/d" "$mbsyncrc" ; rm -f "$mbsyncrc"bu
  220. return 0
  221. else
  222. echo "$mailboxes"
  223. printf "\033[31m\033[31mLog-on not successful.\033[0m\\nIt seems that either you inputted the wrong password or server settings, or there are other requirements for your account out of the control of mutt-wizard.\\n"
  224. return 1
  225. fi ;}
  226. finalize() { echo "$mailboxes" | xargs -I {} mkdir -p "$maildir/$fulladdr/{}/cur" "$maildir/$fulladdr/{}/tmp" "$maildir/$fulladdr/{}/new"
  227. sed -ibu "/$marker/d" "$accdir/$idnum-$fulladdr.muttrc" ; rm -f "$accdir/$idnum-$fulladdr.muttrcbu"
  228. toappend="mailboxes $(echo "$mailboxes" | sed "s/^/\"=/;s/$/\"/" | paste -sd ' ' - )"
  229. for x in $mailboxes; do
  230. case "$x" in
  231. *[Ss][Ee][Nn][Tt]*) setBox record "$x"; formatShortcut s sent "$x" ;;
  232. *[Dd][Rr][Aa][Ff][Tt][Ss]*) setBox postponed "$x"; formatShortcut d drafts "$x" ;;
  233. *[Tt][Rr][Aa][Ss][Hh]*) formatShortcut t trash "$x"; setBox trash "$x" ;;
  234. *[Jj][Uu][Nn][Kk]*) formatShortcut j junk "$x" ;;
  235. *[Aa][Rr][Cc][Hh][Ii][Vv][Ee]*) formatShortcut a archive "$x" ;;
  236. *[Ss][Pp][Aa][Mm]*) formatShortcut S spam "$x" ;;
  237. *[Ii][Nn][Bb][Oo][Xx]*) formatShortcut i inbox "$x"; setBox spoolfile "$x" ;;
  238. esac
  239. done
  240. echo "$toappend" >> "$accdir/$idnum-$fulladdr.muttrc"
  241. [ -z "${online+x}" ] && printf "\033[33mYou should now be able to run \`\033[32mmw -y %s\033[33m\` to begin to download your mail.\033[0m\\n" "$fulladdr"
  242. command -V urlview >/dev/null 2>&1 && [ ! -f "$HOME/.urlview" ] && echo "COMMAND \$BROWSER" > "$HOME/.urlview"
  243. return 0 ;}
  244. notmuchauto() { \
  245. [ -z "$NOTMUCH_CONFIG" ] && NOTMUCH_CONFIG="$HOME/.notmuch-config"
  246. [ -f "$NOTMUCH_CONFIG" ] && return 0
  247. nmbasic="[database]
  248. path=$maildir
  249. [user]
  250. name=$realname
  251. primary_email=$fulladdr
  252. [new]
  253. tags=unread;inbox;
  254. ignore=.mbsyncstate;.uidvalidity
  255. [search]
  256. exclude_tags=deleted;spam;
  257. [maildir]
  258. synchronize_flags=true
  259. [crypto]
  260. gpg_path=$GPG"
  261. echo "$nmbasic" > "$NOTMUCH_CONFIG" ;}
  262. togglecron() { cron="$(mktemp)"
  263. crontab -l > "$cron"
  264. if grep -q mailsync "$cron"; then
  265. echo "Removing automatic mailsync..."
  266. sed -ibu /mailsync/d "$cron"; rm -f "$cron"bu
  267. else
  268. echo "Adding automatic mailsync every ${cronmin:-10} minutes..."
  269. echo "*/${cronmin-10} * * * * $prefix/bin/mailsync" >> "$cron"
  270. fi &&
  271. crontab "$cron"; rm -f "$cron" ;}
  272. setact() { if [ -n "${action+x}" ] && [ "$action" != "$1" ]; then
  273. echo "Running $1 with $action..."
  274. echo "Incompatible options given. Only one action may be specified per run."
  275. return 1
  276. else
  277. action="$1"
  278. fi; }
  279. trap 'echo -e "\033[0m\n"; exit' INT ABRT
  280. while getopts "fplhodTYD:y:i:I:s:S:u:a:n:x:m:t:" o; do case "${o}" in
  281. l) setact list || exit 1 ;;
  282. d) setact delete || exit 1 ;;
  283. D) setact delete || exit 1 ; fulladdr="$OPTARG" ;;
  284. y) setact sync || exit 1 ; fulladdr="$OPTARG" ;;
  285. Y) setact sync || exit 1 ;;
  286. a) setact add || exit 1 ; fulladdr="$OPTARG" ;;
  287. i) setact add || exit 1 ; imap="$OPTARG" ;;
  288. I) setact add || exit 1 ; iport="$OPTARG" ;;
  289. s) setact add || exit 1 ; smtp="$OPTARG" ;;
  290. S) setact add || exit 1 ; sport="$OPTARG" ;;
  291. u) setact add || exit 1 ; login="$OPTARG" ;;
  292. n) setact add || exit 1 ; realname="$OPTARG" ;;
  293. m) setact add || exit 1 ; maxmes="$OPTARG" ;;
  294. o) setact add || exit 1 ; online=True ;;
  295. f) setact add || exit 1 ; force=True ;;
  296. x) setact add || exit 1 ; password="$OPTARG" ;;
  297. t) setact toggle || exit 1 ; cronmin="$OPTARG" ;;
  298. T) setact toggle || exit 1 ;;
  299. p) echo "NOTE: Protonmail users must install and configure Protonmail Bridge first for the first sync to work."
  300. imap="127.0.0.1"
  301. iport="1143"
  302. smtp="127.0.0.1"
  303. sport="1025"
  304. tlsline="tls_fingerprint $(msmtp --serverinfo --host=$smtp --port=$sport --tls --tls-certcheck=off | awk '/SHA256:/ {print $2}')"
  305. setact add || exit 1
  306. ;;
  307. *) cat << EOF
  308. mw: mutt-wizard, auto-configure email accounts for mutt
  309. including downloadable mail with \`isync\`.
  310. Main actions:
  311. -a your@email.com Add an email address
  312. -l List email addresses configured
  313. -d Remove an already added address
  314. -D your@email.com Force remove account without confirmation
  315. -y your@email.com Sync mail for account by name
  316. -Y Sync mail for all accounts
  317. -t number Toggle automatic mailsync every <number> minutes
  318. -T Toggle automatic mailsync
  319. Options allowed with -a:
  320. -u Account login name if not full address
  321. -n "Real name" to be on the email account
  322. -i IMAP server address
  323. -I IMAP server port
  324. -s SMTP server address
  325. -S SMTP server port
  326. -x Password for account (recommended to be in double quotes)
  327. -p Install for a Protonmail account.
  328. -o Configure address, but keep mail online.
  329. -f Assume typical English mailboxes without attempting log-on.
  330. NOTE: Once at least one account is added, you can run
  331. \`mbsync -a\` to begin downloading mail.
  332. To change an account's password, run \`pass edit ${pass_prefix}your@email.com\`.
  333. EOF
  334. exit 1
  335. ;;
  336. esac done
  337. ! command -v mbsync >/dev/null && [ -z "${force+x}" ] && printf "\`mbsync (isync package)\` must be installed to run mutt-wizard.\\n" && exit 1
  338. case "$action" in
  339. list) list ;;
  340. add) askinfo && getprofiles && writeinfo && getboxes && finalize || { delete ; exit 1 ;} ;;
  341. delete) delete $fulladdr ;;
  342. sync) mailsync $fulladdr ;;
  343. toggle) togglecron ;;
  344. esac