#!/bin/sh debug() { echo "fulladdr: $fulladdr" echo "login: $login" echo "title: $title" echo "imap: $imap" echo "iport: $iport" echo "smtp: $smtp" echo "sport: $sport" echo "proton: $proton" echo "tls: $tls" echo "force: $force" echo "online: $online" echo "action: $action" } command -V gpg >/dev/null 2>&1 && GPG="gpg" || GPG="gpg2" [ -z ${PASSWORD_STORE_DIR+x} ] && PASSWORD_STORE_DIR="$HOME/.password-store" [ -r "$PASSWORD_STORE_DIR/.gpg-id" ] && "$GPG" --list-secret-keys $(cat "$PASSWORD_STORE_DIR/.gpg-id") >/dev/null 2>&1 || { printf "\`pass\` must be installed and initialized to encrypt passwords.\\nBe sure it is installed and run \`pass init \`.\\nIf you don't have a GPG public private key pair, run \`%s --full-gen-key\` first.\\n" "$GPG" exit } ! command -v mbsync >/dev/null && printf "\`mbsync (isync package)\` must be installed to run mutt-wizard.\\n" && exit prefix="/usr/local" pass_prefix="mw-" muttdir="${XDG_CONFIG_HOME:-$HOME/.config}/mutt" # Main mutt config location accdir="$muttdir/accounts" # Directory for account settings maildir="${XDG_DATA_HOME:-$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="$prefix/share/mutt-wizard" mbsyncrc="${MBSYNCRC:-$HOME/.mbsyncrc}" mwconfig="$muttshare/mutt-wizard.muttrc" cachedir="${XDG_CACHE_HOME:-$HOME/.cache}/mutt-wizard" muttrc="$muttdir/muttrc" msmtprc="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/config" msmtplog="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/msmtp.log" ssltype="IMAPS" # This is later changed to `None` later in the script if using Protonmail MARKER="# mw-autogenerated" alias mbsync='mbsync -c "$mbsyncrc"' 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/" do [ -f "$x" ] && sslcert="$x" && break done || { echo "CA Certificate not found. Please install one or link it to /etc/ssl/certs/ca-certificates.crt" && exit 1 ;} getaccounts() { accounts="$(find "$accdir" -type f | grep -o "[0-9]-.*.muttrc" | sed "s/-/: /;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 $msmtplog " msmtp_profile="account $title host $smtp port ${sport:-587} from $fulladdr user $login passwordeval \"pass $pass_prefix$title\" $starttlsoff " mbsync_profile="IMAPStore $title-remote Host $imap Port ${iport:-993} User $login PassCmd \"pass $pass_prefix$title\" AuthMechs LOGIN SSLType $ssltype CertificateFile $sslcert MaildirStore $title-local Subfolders Verbatim Path ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$title/ Inbox ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$title/INBOX Flatten . Channel $title Expunge Both Master :$title-remote: Slave :$title-local: Patterns * !\"[Gmail]/All Mail\" Create Both SyncState * MaxMessages $maxmes ExpireUnread no # End profile " if [ -z "${online+x}" ]; then mutt_profile="# vim: filetype=neomuttrc # muttrc file for account $title set realname = \"$realname\" set from = \"$fulladdr\" set sendmail = \"msmtp -a $title\" alias me $realname <$fulladdr> set folder = \"$maildir/$title\" set header_cache = $cachedir/$title/headers set message_cachedir = $cachedir/$title/bodies 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 \"mbsync -V $title\" \"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 = \"msmtp -a $title\" alias me $realname <$fulladdr> set folder = \"imaps://$login@$imap:${iport:-993}\" set imap_user = \"$login\" set header_cache = $cachedir/$title/headers set message_cachedir = $cachedir/$title/bodies set imap_pass = \"\`pass $pass_prefix$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" } parsedomains(){ serverinfo="$(grep "^${fulladdr#*@}" "$muttshare/domains.csv" 2>/dev/null)" [ -z "$serverinfo" ] && serverinfo="$(grep "$(echo "${fulladdr#*@}" | sed "s/\.[^\.]*$/\.\\\*/")" "$muttshare/domains.csv" 2>/dev/null)" IFS=, read -r service imapsugg iportsugg smtpsugg sportsugg </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 [ -z "$login" ] && echo "Give the account log-on/username for this address:" && read -r login login="${login:-$fulladdr}" #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.ch|protonmail.com|pm.me) printf "\033[31mREMEMBER: Protonmail users must install and configure Protonmail Bridge first for the sync to work:\\nhttps://protonmail.com/bridge/\\n\033[0m" && ssltype="None" ;; #esac getpass } writeinfo() { # Insert account information into variables. getprofiles # Create required directories. mkdir -p "$muttdir" "$accdir" "$cachedir/$title/bodies" "${XDG_CONFIG_HOME:-$HOME/.config}/msmtp" "$maildir/$title" # Get accounts and find the first missing account number (max. 9). getaccounts for x in $(seq 1 9); do echo "$accounts" | grep -q "$x" || { export idnum="$x"; break ;}; done # Create msmtprc file if not present. [ ! -f "$msmtprc" ] && echo "$msmtp_header" > "$msmtprc" # Add account msmtp settings. echo "$msmtp_profile" >> "$msmtprc" # On Ubuntu/Debian, a link is needed since they use an older version. command -V apt-get >/dev/null 2>&1 && ln -s "$msmtprc" "$HOME/.msmtprc" 2>/dev/null # Create the individual mutt config file for the account. echo "$mutt_profile" > "$accdir/$idnum-$title.muttrc" # Create the mbsync config file. mkdir -p "${mbsyncrc%/*}" echo "$mbsync_profile" >> "$mbsyncrc" # Create a notmuch config file if not present already. notmuchauto # Create a basic muttrc is not present and source the mutt-wizard files # and add the shortcuts to the account. [ ! -f "$muttrc" ] && echo "# vim: filetype=neomuttrc" > "$muttrc" && echo "muttrc created." ! grep -q "^source.*mutt-wizard.muttrc" "$muttrc" && echo "source $mwconfig $MARKER" >> "$muttrc" ! grep "^source.*.muttrc" "$muttrc" | grep -qv "$mwconfig" && echo "source $accdir/$idnum-$title.muttrc $MARKER" >> "$muttrc" echo "macro index,pager i$idnum 'source $accdir/$idnum-$title.muttrc!;' \"switch to $fulladdr\" $MARKER" >> "$muttrc" } protonfinger() { printf "Getting Protonmail bridge fingerprint...\\n" fingerprint="$(msmtp --serverinfo --host=127.0.0.1 --port=1025 --tls --tls-certcheck=off | grep SHA256: | sed 's/^.*: //')" sed -ibu "s/account $title/&\ntls_trust_file\ntls_fingerprint $fingerprint/" "$msmtprc" ; rm -f "$msmtprc"bu } getpass() { while : ; do pass rm -f "$pass_prefix$title" >/dev/null 2>&1 pass insert "$pass_prefix$title" && break; done ;} formatShortcut() { toappend="$toappend macro index,pager g$1 \"=$3\" \"go to $2\" $MARKER getpass macro index,pager M$1 \";=$3\" \"move mail to $2\" $MARKER getpass macro index,pager C$1 \";=$3\" \"copy mail to $2\" $MARKER" >> "$accdir/$idnum-$title.muttrc" } setBox() { toappend="$toappend set $1 = \"+$2\" $MARKER" ;} getboxes() { [ -n "${force+x}" ] && mailboxes="INBOX Drafts Junk Sent Archive" && return 0 if mailboxes="$(mbsync -l "$title" | sed 's/\//./')" >/dev/null 2>&1 && [ -n "$mailboxes" ]; then [ "$accounttype" = "online" ] && sed -ibu "/IMAPStore $title-remote$/,/# End profile/d" "$mbsyncrc" ; rm -f "$mbsyncrc"bu printf "\033[32mMailboxes detected.\033[0m\\n" return 0 else 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" return 1 fi ;} finalize() { \ # Create the required mailbox structure. echo "$mailboxes" | xargs -I {} mkdir -p "$maildir/$title/{}" printf "Setting default mailboxes for your Inbox, Sent, Drafts and Trash in mutt...\\n" sed -ibu "/$MARKER/d" "$accdir/$idnum-$title.muttrc" ; rm -f "$accdir/$idnum-$title.muttrcbu" toappend="mailboxes $(echo "$mailboxes" | sed "s/^/\"=/;s/$/\"/" | paste -sd ' ' )" for x in $mailboxes; do case $x in *[Ii][Nn][Bb][Oo][Xx]*) formatShortcut i inbox "$x"; setBox spoolfile "$x" ;; *[Ss][Ee][Nn][Tt]*) setBox record "$x"; formatShortcut s sent "$x" ;; *[Dd][Rr][Aa][Ff][Tt][Ss]*) setBox postponed "$x"; formatShortcut d drafts "$x" ;; *[Tt][Rr][Aa][Ss][Hh]*|*[Jj][Uu][Nn][Kk]*) formatShortcut t trash "$x"; setBox trash "$x" ;; *[Aa][Rr][Cc][Hh][Ii][Vv][Ee]*) formatShortcut a archive "$x" ;; *[Ss][Pp][Aa][Mm]*) formatShortcut S spam "$x" ;; esac done echo "$toappend" >> "$accdir/$idnum-$title.muttrc" [ -z "${online+x}" ] && 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" # Create a urlview config file if non-existent. command -V urlview >/dev/null 2>&1 && [ ! -f "$HOME/.urlview" ] && echo "COMMAND \$BROWSER" > "$HOME/.urlview" return 0 } confirm() { printf "Do you want to %s? [yes/N]\\n\t" "$@" && read -r input && ! echo "$input" | grep -qi "^yes$" && 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 -qi "^yes$" && 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 -ibu "/IMAPStore $title-remote$/,/# End profile/d" "$mbsyncrc" ; rm -rf "$mbsyncrc"bu rm -rf "${cachedir:?}/${title:?}" "$accdir/"[1-9]"-$title.muttrc" sed -ibu "/[0-9]-$title.muttrc/d" "$muttrc" ; rm -f "$muttrc"bu sed -ibu "/account $title/,/^\(\s*$\|account\)/d" "$msmtprc"; rm -f "$msmtprc"bu } syncwrapper() { mbsync "${1:--a}" & ( kill -46 "$(pidof "${STATUSBAR:-dwmblocks}")" >/dev/null 2>&1 ) 2>/dev/null wait ( kill -46 "$(pidof "${STATUSBAR:-dwmblocks}")" >/dev/null 2>&1 ) 2>/dev/null notmuch new } purge() { confirm "delete all account data" || exit rm -rf "$mbsyncrc" "$accdir" "${XDG_CONFIG_HOME:-$HOME/.config}/msmtp" "$cachedir" echo "All configs and account settings have been purged." sed -ibu "/$MARKER/d" "$muttrc" ; rm -f "$muttrc"bu } notmuchauto() { \ [ -z "$NOTMUCH_CONFIG" ] && NOTMUCH_CONFIG="$HOME/.notmuch-config" [ -f "$NOTMUCH_CONFIG" ] && return 0 nmbasic="[database] path=$maildir [user] name=$realname primary_email=$fulladdr [new] tags=unread;inbox; ignore=.mbsyncstate;.uidvalidity [search] exclude_tags=deleted;spam; [maildir] synchronize_flags=true [crypto] gpg_path=$GPG" echo "$nmbasic" > "$NOTMUCH_CONFIG" ;} trap 'echo -e "\033[0m\n"; exit' INT ABRT setaction() { if [ -n "${action+x}" ] && [ "$action" != "$1" ]; then echo "Running $1 with $action..." echo "Incompatible options given. Only one action may be specified per run." return 1 else action="$1" fi; } while getopts "gbpPlhdYD:y:i:I:s:S:u:a:" o; do case "${o}" in l) setaction list || exit 1 ;; p) setaction pass || exit 1 ;; d) setaction delete || exit 1 ;; D) setaction delete || exit 1 ; title="$OPTARG" ;; y) setaction sync || exit 1 ; title="$OPTARG" ;; Y) setaction sync || exit 1 ;; a) setaction add || exit 1 ; fulladdr="$OPTARG" ;; i) setaction add || exit 1 ; imap="$OPTARG" ;; I) setaction add || exit 1 ; iport="$OPTARG" ;; s) setaction add || exit 1 ; smtp="$OPTARG" ;; S) setaction add || exit 1 ; sport="$OPTARG" ;; u) setaction add || exit 1 ; login="$OPTARG" ;; o) setaction add || exit 1 ; online=True ;; b) setaction add || exit 1 ; force=True ;; P) echo "NOTE: Protonmail users must install and configure Protonmail Bridge first for the first sync to work." proton=True imap="127.0.0.1" iport=1143 smtp="127.0.0.1" sport=1025 setaction add || exit 1 ;; g) debug ;; *) cat << EOF mw: mutt-wizard, auto-configure email accounts for mutt including downloadable mail with \`isync\`. Main actions: -a your@email.com Add an email address -d Remove an already added address -D nameofaccount Force remove account without confirmation -l List email addresses configured -y nameofaccount Sync mail for account by name -Y Sync mail for all accounts Options allowed with -a: -u Account login name if not full address. -i IMAP server address -I IMAP server port -s SMTP server address -S SMTP server port -p Install for a Protonmail account. -o Configure address, but keep mail online. -b Assume typical English mailboxes without attempting log-on. NOTE: Once at least one account is added, you can run \`mbsync -a\` to begin downloading mail. EOF ;; esac done case "$action" in list) list ;; add) askinfo && writeinfo && getboxes && finalize || delete ;; pass) pick "change the password of" && getpass ;; delete) pick delete && confirm "delete the \`$title\` profile" && delete ;; sync) syncwrapper $title ;; purge) purge ;; esac