diff options
author | Wayne Reeves <darthwayne@hotmail.com> | 2022-08-17 19:14:40 -0500 |
---|---|---|
committer | Wayne Reeves <darthwayne@hotmail.com> | 2022-08-17 19:14:40 -0500 |
commit | a47042582c87af98aef1999f6b64b20b1d6c5cde (patch) | |
tree | efc49be7da040b49f85ae73509e2c70ce8d01fd7 /bin | |
parent | d4041b5953e0bebf86c85f9a29e25ad7f8af74dc (diff) | |
parent | 110a6ce78549eeef58dac1f9dd283da5f99c5cd3 (diff) |
Merge remote-tracking branch 'origin/master' into HEAD
Diffstat (limited to 'bin')
-rwxr-xr-x | bin/mailsync | 92 | ||||
-rwxr-xr-x | bin/mw | 596 | ||||
-rwxr-xr-x | bin/openfile | 9 |
3 files changed, 352 insertions, 345 deletions
diff --git a/bin/mailsync b/bin/mailsync index 93ec35d..854e1d1 100755 --- a/bin/mailsync +++ b/bin/mailsync @@ -1,71 +1,85 @@ #!/bin/sh -# Sync mail and give notification if there is new mail. +# - Syncs mail for all accounts, or a single account given as an argument. +# - Displays a notification showing the number of new mails. +# - Displays a notification for each new mail with its subject displayed. +# - Runs notmuch to index new mail. +# - This script can be set up as a cron job for automated mail syncing. + +# There are many arbitrary and ugly features in this script because it is +# inherently difficult to pass environmental variables to cronjobs and other +# issues. It also should at least be compatible with Linux (and maybe BSD) with +# Xorg and MacOS as well. -# Run only if user logged in (prevent cron errors) -pgrep -u "${USER:=$LOGNAME}" >/dev/null || { echo "$USER not logged in; sync will not run."; exit ;} # Run only if not already running in other instance -pgrep -x mbsync >/dev/null && { echo "mbsync is already running." ; exit ;} +pgrep mbsync >/dev/null && { echo "mbsync is already running."; exit ;} + +# First, we have to get the right variables for the mbsync file, the pass +# archive, notmuch and the GPG home. This is done by searching common profile +# files for variable assignments. This is ugly, but there are few options that +# will work on the maximum number of machines. +eval "$(grep -h -- \ + "^\s*\(export \)\?\(MBSYNCRC\|PASSWORD_STORE_DIR\|NOTMUCH_CONFIG\|GNUPGHOME\)=" \ + "$HOME/.profile" "$HOME/.bash_profile" "$HOME/.zprofile" "$HOME/.config/zsh/.zprofile" "$HOME/.zshenv" \ + "$HOME/.config/zsh/.zshenv" "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.config/zsh/.zshrc" \ + "$HOME/.pam_environment" 2>/dev/null)" -# Checks for internet connection and set notification script. -ping -q -c 1 1.1.1.1 > /dev/null || ping -q -c 1 1.0.0.1 > /dev/null || ping -q -c 1 example.org || { echo "No internet connection detected."; exit ;} -command -v notify-send >/dev/null || echo "Note that \`libnotify\` or \`libnotify-send\` should be installed for pop-up mail notifications with this script." +export GPG_TTY="$(tty)" -# Required to display notifications if run as a cronjob: -export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus -export DISPLAY=:0.0 +[ -n "$MBSYNCRC" ] && alias mbsync="mbsync -c $MBSYNCRC" || MBSYNCRC="$HOME/.mbsyncrc" -# For individual configurations: -[ -d "$HOME/.local/share/password-store" ] && export PASSWORD_STORE_DIR="$HOME/.local/share/password-store" +lastrun="${XDG_CONFIG_HOME:-$HOME/.config}/mutt/.mailsynclastrun" # Settings are different for MacOS (Darwin) systems. -if [ "$(uname)" = "Darwin" ]; then - notify() { osascript -e "display notification \"$2 in $1\" with title \"You've got Mail\" subtitle \"Account: $account\"" && sleep 2 ;} - messageinfo() { osascript -e "display notification with title \"📧 $from\" subtitle \"$subject\"" ;} -else - notify() { notify-send --app-name="mutt-wizard" "mutt-wizard" "📬 $2 new mail(s) in \`$1\` account." ;} - messageinfo() { notify-send --app-name="mutt-wizard" "📧$from:" "$subject" ;} -fi +case "$(uname)" in + Darwin) + notify() { osascript -e "display notification \"$2 in $1\" with title \"You've got Mail\" subtitle \"Account: $account\"" && sleep 2 ;} + ;; + *) + case "$(readlink -f /sbin/init)" in + *systemd*|*openrc*) export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus ;; + esac + # remember if a display server is running since `ps` doesn't always contain a display + pgrepoutput="$(pgrep -ax X\(\|org\|wayland\))" + displays="$(echo "$pgrepoutput" | grep -wo "[0-9]*:[0-9]\+" | sort -u)" + notify() { [ -n "$pgrepoutput" ] && for x in ${displays:-0:}; do + export DISPLAY=$x + notify-send --app-name="mutt-wizard" "New mail!" "📬 $2 new mail(s) in \`$1\` account." + done ;} + ;; +esac # Check account for new mail. Notify if there is new content. syncandnotify() { acc="$(echo "$account" | sed "s/.*\///")" if [ -z "$opts" ]; then mbsync "$acc"; else mbsync "$opts" "$acc"; fi - new=$(find "$HOME/.local/share/mail/$acc/INBOX/new/" "$HOME/.local/share/mail/$acc/Inbox/new/" "$HOME/.local/share/mail/$acc/inbox/new/" -type f -newer "$HOME/.config/mutt/.mailsynclastrun" 2> /dev/null) + new=$(find\ + "$HOME/.local/share/mail/$acc/"[Ii][Nn][Bb][Oo][Xx]/new/\ + "$HOME/.local/share/mail/$acc/"[Ii][Nn][Bb][Oo][Xx]/cur/\ + -type f -newer "$lastrun" 2> /dev/null) newcount=$(echo "$new" | sed '/^\s*$/d' | wc -l) - if [ "$newcount" -gt "0" ]; then - notify "$acc" "$newcount" & - for file in $new; do - # Extract subject and sender from mail. - from=$(awk '/^From: / && ++n ==1,/^\<.*\>:/' "$file" | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | awk '{ $1=""; if (NF>=3)$NF=""; print $0 }' | sed 's/^[[:blank:]]*[\"'\''\<]*//;s/[\"'\''\>]*[[:blank:]]*$//') - subject=$(awk '/^Subject: / && ++n == 1,/^\<.*\>: / && ++i == 2' "$file" | head -n 1 | perl -CS -MEncode -ne 'print decode("MIME-Header", $_)' | sed 's/^Subject: //' | sed 's/^{[[:blank:]]*[\"'\''\<]*//;s/[\"'\''\>]*[[:blank:]]*$//' | tr -d '\n') - messageinfo & - done - fi + case 1 in + $((newcount > 0)) ) notify "$acc" "$newcount" ;; + esac } # Sync accounts passed as argument or all. -if [ "$#" -eq "0" ]; then - accounts="$(awk '/^Channel/ {print $2}' "$HOME/.mbsyncrc")" -else +if [ "$#" -gt "0" ]; then for arg in "$@"; do [ "${arg%${arg#?}}" = '-' ] && opts="${opts:+${opts} }${arg}" && shift 1 done accounts=$* fi - -( kill -46 "$(pidof "${STATUSBAR:-dwmblocks}")" >/dev/null 2>&1 ) 2>/dev/null +[ -z "$accounts" ] && accounts="$(awk '/^Channel/ {print $2}' "$MBSYNCRC")" # Parallelize multiple accounts -for account in $accounts -do +for account in $accounts; do syncandnotify & done wait -( kill -46 "$(pidof "${STATUSBAR:-dwmblocks}")" >/dev/null 2>&1 ) 2>/dev/null -notmuch new 2>/dev/null +notmuch new --quiet #Create a touch file that indicates the time of the last run of mailsync -touch "$HOME/.config/mutt/.mailsynclastrun" +touch "$lastrun" @@ -1,332 +1,247 @@ #!/bin/sh -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 <yourgpgemail>\`.\\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" -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 +maildir="${XDG_DATA_HOME:-$HOME/.local/share}/mail" muttshare="$prefix/share/mutt-wizard" -mbsyncrc="$HOME/.mbsyncrc" -mwconfig="$muttshare/mutt-wizard.muttrc" -cachedir="$HOME/.cache/mutt-wizard" -muttrc="$muttdir/muttrc" -msmtprc="$HOME/.config/msmtp/config" -ssltype="IMAPS" # This is later changed to `None` later in the script if using Protonmail - -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 +cachedir="${XDG_CACHE_HOME:-$HOME/.cache}/mutt-wizard" +muttrc="${XDG_CONFIG_HOME:-$HOME/.config}/mutt/muttrc" +accdir="${XDG_CONFIG_HOME:-$HOME/.config}/mutt/accounts" +msmtprc="${XDG_CONFIG_HOME:-$HOME/.config}/msmtp/config" +msmtplog="${XDG_CACHE_HOME:-$HOME/.cache}/msmtp/msmtp.log" +mbsyncrc="${MBSYNCRC:-$HOME/.mbsyncrc}" +mpoprc="${XDG_CONFIG_HOME:-$HOME/.config}/mpop/config" +alias mbsync='mbsync -c "$mbsyncrc"' + +# On Ubuntu/Debian, a link is needed since they use an older version. +if command -V apt-get >/dev/null 2>&1; then + master="Master" + slave="Slave" +fi + +for x in "/etc/ssl/certs/ca-certificates.crt" \ + "/etc/pki/tls/certs/ca-bundle.crt" "/etc/ssl/cert.pem" \ + "/etc/ssl/ca-bundle.pem" "/etc/pki/tls/cacert.pem" \ + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.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" ;} +checkbasics() { command -V gpg >/dev/null 2>&1 && GPG="gpg" || GPG="gpg2" + PASSWORD_STORE_DIR="${PASSWORD_STORE_DIR:-$HOME/.password-store}" + [ -r "$PASSWORD_STORE_DIR/.gpg-id" ] || { + echo "First run \`pass init <yourgpgemail>\` to set up a password archive." + echo "(If you don't already have a GPG key pair, first run \`$GPG --full-generate-key\`.)" + exit 1 ;} ;} -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 +getaccounts() { accounts="$(find -L "$accdir" -type f 2>/dev/null | grep -o "\S*.muttrc" | sed "s|.*/\([0-9]-\)*||;s/\.muttrc$//" | nl)" ;} + +list() { getaccounts && [ -n "$accounts" ] && echo "$accounts" || exit 1 ;} + +prepmsmtp() { mkdir -p "${msmtprc%/*}" "${msmtplog%/*}" + ln -s "$msmtprc" "$HOME/.msmtprc" 2>/dev/null + echo "account $fulladdr host $smtp -port $sport +port ${sport:-465} from $fulladdr user $login -passwordeval \"pass mutt-wizard-$title\" -$starttlsoff -" -mbsync_profile="IMAPStore $title-remote +passwordeval \"pass $passprefix$fulladdr\" +auth ${auth:-on} +tls on +tls_trust_file $sslcert +logfile $msmtplog +${tlsline:-tls_starttls off} +" >> "$msmtprc" +} + +prepmbsync() { mkdir -p "${mbsyncrc%/*}" + echo " +IMAPStore $fulladdr-remote Host $imap -Port $iport +Port ${iport:-993} User $login -PassCmd \"pass mutt-wizard-$title\" +PassCmd \"pass $passprefix$fulladdr\" AuthMechs LOGIN -SSLType $ssltype +SSLType ${imapssl:-IMAPS} CertificateFile $sslcert -MaildirStore $title-local +MaildirStore $fulladdr-local Subfolders Verbatim -Path ~/.local/share/mail/$title/ -Inbox ~/.local/share/mail/$title/INBOX -Flatten . +Path ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$fulladdr/ +Inbox ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$fulladdr/${inbox:-INBOX} -Channel $title +Channel $fulladdr Expunge Both -Master :$title-remote: -Slave :$title-local: +${master:-Far} :$fulladdr-remote: +${slave:-Near} :$fulladdr-local: Patterns * !\"[Gmail]/All Mail\" Create Both SyncState * -MaxMessages $maxmes +MaxMessages ${maxmes:-0} ExpireUnread no # End profile -" +" >> "$mbsyncrc" ;} + +prepmpop() { mkdir -p "${mpoprc%/*}" + echo " +account $fulladdr +tls on +user $login +host $imap +delivery maildir ${XDG_DATA_HOME:-$HOME/.local/share}/mail/$fulladdr/${inbox:-INBOX} +passwordeval pass $passprefix$fulladdr +" >> "$mpoprc" ;} -if [ "$accounttype" = "offline" ]; then -mutt_profile="# vim: filetype=neomuttrc -# muttrc file for account $title +prepmutt() { mkdir -p "${muttrc%/*}" "$accdir" + echo "# vim: filetype=neomuttrc +# muttrc file for account $fulladdr set realname = \"$realname\" set from = \"$fulladdr\" -set sendmail = \"msmtp -a $title\" +set sendmail = \"msmtp -a $fulladdr\" alias me $realname <$fulladdr> -set folder = \"$maildir/$title\" -set header_cache = $cachedir/$title/headers -set message_cachedir = $cachedir/$title/bodies +set folder = \"$folder\" +set header_cache = $cachedir/$fulladdr/headers +set message_cachedir = $cachedir/$fulladdr/bodies set mbox_type = Maildir +set hostname = \"$hostname\" +source $muttshare/switch.muttrc +set spoolfile = "+INBOX" +set postponed = "+Drafts" +set trash = "+Trash" +set record = "+Sent" +$extra +$synccmd +macro index \eg \"<enter-command>unset wait_key<enter><shell-escape>gpg --list-secret-keys; printf 'Enter email ID of user to publish: '; read eID; printf 'Enter fingerprint of GPG key to publish: '; read eFGPT; $prefix/libexec/gpg-wks-client --create \\\$eFGPT \\\$eID | msmtp --read-envelope-from --read-recipients -a $fulladdr<enter>\" \"publish GPG key to WKS provider\" +macro index \eh \"<pipe-message>$prefix/libexec/gpg-wks-client --receive | msmtp --read-envelope-from --read-recipients -a $fulladdr<enter>\" \"confirm GPG publication\" +" > "$accdir/$fulladdr.muttrc" -set crypt_autosign = yes -set crypt_opportunistic_encrypt = yes -set pgp_self_encrypt = yes -set pgp_default_key = $keyid - -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 = \"msmtp -a $title\" -alias me $realname <$fulladdr> -set folder = \"imaps://$login@$imap:$iport\" -set imap_user = \"$login\" -set header_cache = $cachedir/$title/headers -set message_cachedir = $cachedir/$title/bodies -set imap_pass = \"\`pass mutt-wizard-$title\`\" + [ ! -f "$muttrc" ] && echo "# vim: filetype=neomuttrc" > "$muttrc" + ! grep -q "^source.*mutt-wizard.muttrc" "$muttrc" && echo "source $muttshare/mutt-wizard.muttrc" >> "$muttrc" + ! grep "^source.*.muttrc" "$muttrc" | grep -qv "$muttshare/mutt-wizard.muttrc" && echo "source $accdir/$fulladdr.muttrc" >> "$muttrc" + echo "macro index,pager i$idnum '<sync-mailbox><enter-command>source $accdir/$fulladdr.muttrc<enter><change-folder>!<enter>;<check-stats>' \"switch to $fulladdr\"" >> "$muttrc" +} -set crypt_autosign = yes -set crypt_opportunistic_encrypt = yes -set pgp_self_encrypt = yes -set pgp_default_key = $keyid +getprofiles() { \ + case "$iport" in + 1143) imapssl=None ;; + 143) imapssl=STARTTLS ;; + esac + case "$type" in + online) folder="imaps://$login@$imap:${iport:-993}" +extra="set imap_user = \"$login\" +set imap_pass = \"\`pass $passprefix$fulladdr\`\" +set ssl_starttls = yes +set ssl_force_tls = yes" + ;; + pop) synccmd="macro index o \"<shell-escape>mpop $fulladdr<enter>\" \"run mpop to get $fulladdr's mail\"" + folder="$maildir/$fulladdr" + prepmpop ;; + *) synccmd="macro index o \"<shell-escape>mw -y $fulladdr<enter>\" \"run mbsync to sync $fulladdr\"" + folder="$maildir/$fulladdr" + prepmbsync ;; + esac + prepmsmtp + prepmutt + prepnotmuch # Create a notmuch config file if not present already. +} +parsedomains(){ serverinfo="$(grep "^${fulladdr#*@}" "$muttshare/domains.csv" 2>/dev/null)" -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" + [ -z "$serverinfo" ] && serverinfo="$(grep "$(echo "${fulladdr#*@}" | sed "s/\.[^\.]*$/\.\\\*/")" "$muttshare/domains.csv" 2>/dev/null)" + + IFS=, read -r service imapsugg iportsugg smtpsugg sportsugg <<EOF +$serverinfo +EOF + imap="${imap:-$imapsugg}" + smtp="${smtp:-$smtpsugg}" + sport="${sport:-$sportsugg}" + iport="${iport:-$iportsugg}" +} + +delete() { if [ -z "${fulladdr+x}" ]; then + echo "Select the account you would like to delete (by number):" + list || exit 1 + read -r input + match="^\s*$input\s\+" + else + match="\s\+$fulladdr$" + getaccounts + fi + + fulladdr="$(echo "$accounts" | grep "$match" | grep -o "\S*@\S*")" + + [ -z "$fulladdr" ] && echo "$fulladdr is not a valid account name." && return 1 + + sed -ibu "/IMAPStore $fulladdr-remote$/,/# End profile/d" "$mbsyncrc" 2>/dev/null ; rm -f "$mbsyncrc"bu + rm -rf "${cachedir:?}/${fulladdr:?}" "$accdir/$fulladdr.muttrc" "$accdir/"[0-9]-"$fulladdr.muttrc" + sed -ibu "/\([0-9]-\)\?$fulladdr.muttrc/d" "$muttrc" 2>/dev/null; rm -f "$muttrc"bu + sed -ibu "/account $fulladdr$/,/^\(\s*$\|account\)/d" "$msmtprc" 2>/dev/null; rm -f "$msmtprc"bu + sed -ibu "/account $fulladdr$/,/^\(\s*$\|account\)/d" "$mpoprc" 2>/dev/null; rm -f "$mpoprc"bu + pass rm -f "$passprefix$fulladdr" >/dev/null 2>&1 + [ -n "${purge+x}" ] && rm -rf "${maildir:?}/${fulladdr:?}" + + for file in "$msmtprc" "$mbsyncrc" "$mpoprc"; do + sed -ibu 'N;/^\n$/D;P;D;' "$file" 2>/dev/null; rm -f "$file"bu + done } askinfo() { \ - printf "Insert the \033[31memail address\033[0m that you want to autoconfigure for mutt/mbsync\\n\tEmail: \033[36m" - read -r fulladdr - keyid=$("$GPG" --list-keys --with-colons "$fulladdr" | awk -F: '/^pub:/ { print $5 }') - 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" + [ -z "$fulladdr" ] && echo "Give the full email address to add:" && + read -r fulladdr + while ! echo "$fulladdr" | grep -qE "^.+@.+\.[A-Za-z]+$"; do + echo "$fulladdr is not a valid email address. Please retype the address:" read -r fulladdr - printf "\033[0m" done - domain="$(echo "$fulladdr" | sed "s/.*@//")" - search_query=$domain - case "$domain" in - protonmail.com|protonmail.ch|pm.me) - search_query='protonmail.com' ;; - *) - while : ; do - printf "\nIs your email hosted with Protonmail? [yes/no] " - read -r is_protonmail - case $is_protonmail in - [Yy][Ee][Ss]) search_query='protonmail.com' && break;; - [Nn][Oo]) break;; - *) printf 'Please answer Yes or No' - esac; done; - esac - printf "\\nSearching for \033[32m%s\033[0m in \033[34m\`domains.csv\`\033[0m..." "$domain" - serverinfo="$(grep "^$search_query" "$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" + getaccounts; echo "$accounts" | grep -q "\s$fulladdr$" 2>/dev/null && + { echo "$fulladdr has already been added" && exit 1 ;} + { [ -z "$imap" ] || [ -z "$smtp" ] ;} && parsedomains + [ -z "$imap" ] && echo "Give your email server's IMAP address (excluding the port number):" && 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" + [ -z "$smtp" ] && echo "Give your email server's SMTP address (excluding the port number):" && 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" + [ "$sport" = 587 ] && tlsline="# tls_starttls" + [ -z "$realname" ] && realname="${fulladdr%%@*}" + [ -z "$passprefix" ] && passprefix="" + hostname="${fulladdr#*@}" + login="${login:-$fulladdr}" + if [ -n "${password+x}" ]; then + createpass else - IFS=, read -r service imap iport smtp sport <<EOF -$serverinfo -EOF - printf "\\n\033[3;33mCongrats!\033[0m Server info has automatically been 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.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 - [ "$sport" = 465 ] && starttlsoff="tls_starttls off" + getpass 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" - [ "$accounttype" = "offline" ] && printf "If you want to limit the number of messages kept offline to a number, enter that number below. If you do not want to limit your mail and would like \`mbsync\` to sync all mail, press enter without typing a number.\\n\t" && read -r maxmes - echo "$maxmes" | grep "[1-9]" >/dev/null || maxmes="0" - getpass - getprofiles - mkdir -p "$muttdir" "$accdir" "$cachedir/$title/bodies" "$HOME/.config/msmtp" - getaccounts - for x in $(seq 1 9); do echo "$accounts" | grep "$x" >/dev/null 2>&1 || { export idnum="$x"; break ;}; done - [ ! -f "$msmtprc" ] && echo "$msmtp_header" > "$msmtprc" - echo "$msmtp_profile" >> "$msmtprc" - command -V apt-get >/dev/null 2>&1 && ln -s "$msmtprc" "$HOME/.msmtprc" 2>/dev/null - case "$service" in - protonmail.ch|protonmail.com|pm.me) protonfinger || return 1 ;; - esac - echo "$mutt_profile" > "$accdir/$idnum-$title.muttrc" - echo "$mbsync_profile" >> "$mbsyncrc" - notmuchauto - [ ! -f "$muttrc" ] && echo "# vim: filetype=neomuttrc" > "$muttrc" && echo "muttrc created." - ! grep "^source.*mutt-wizard.muttrc" "$muttrc" >/dev/null && echo "source $mwconfig # mw-autogenerated" >> "$muttrc" - ! 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" } -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 -} +createpass() { echo "$password" > "$PASSWORD_STORE_DIR/$passprefix$fulladdr" + "$GPG" -qe $(printf -- " -r %s" $(cat "$PASSWORD_STORE_DIR/.gpg-id")) "$PASSWORD_STORE_DIR/$passprefix$fulladdr" + rm -f "$PASSWORD_STORE_DIR/$passprefix$fulladdr" ;} + +getpass() { while : ; do pass rm -f "$passprefix$fulladdr" >/dev/null 2>&1 + pass insert -f "$passprefix$fulladdr" && break; done ;} -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 && [ -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" - echo "$mailboxes" | xargs -I {} mkdir -p "$maildir/$title/{}" - return 0 +getboxes() { if [ -n "${force+x}" ] ; then + mailboxes="$(printf "INBOX\\nDrafts\\nJunk\\nTrash\\nSent\\nArchive")" 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() { \ - boxes="$(find "$maildir/$title/" -mindepth 1 -type d | sed "s/\ /\\\ /g;s/^.*\//=/;/=\(cur\|new\|tmp\)$/d")" - [ -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 default mailboxes for your Inbox, Sent, Drafts and Trash in mutt...\\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 -ibu "/^mailboxes\|^set record\|^set postponed\|^set trash\|^set spoolfile/d" "$accdir/$idnum-$title.muttrc" ; rm -f "$accdir/$idnum-$title.muttrcbu" - { echo "set spoolfile = \"$spoolfile\""; echo "set record = \"$record\""; echo "set postponed = \"$postponed\""; echo "set trash = \"$trash\""; } >> "$accdir/$idnum-$title.muttrc" - echo "mailboxes $(echo "$boxes" | sed -e "s/^\|$/\"/g" | tr "\n" " ")" >> "$accdir/$idnum-$title.muttrc" - printf "Setting up your keyboard shortcuts for jumping between mailboxes...\\n" - sed -ibu "/# mw-autogenerated/d" "$accdir/$idnum-$title.muttrc" ; rm -f "$accdir/$idnum-$title.muttrcbu" - echo "$boxes" | grep -i inbox | head -n 1 | formatShortcut i inbox - echo "$boxes" | grep -i sent | head -n 1 | formatShortcut s sent - echo "$boxes" | grep -i draft | head -n 1 | formatShortcut d drafts - echo "$boxes" | grep -i trash | head -n 1 | formatShortcut t trash - echo "$boxes" | grep -i spam | head -n 1 | formatShortcut S spam - echo "$boxes" | grep -i junk | head -n 1 | formatShortcut j junk - echo "$boxes" | grep -i archive | head -n 1 | 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" - command -V urlview >/dev/null 2>&1 && [ ! -f "$HOME/.urlview" ] && echo "COMMAND \$BROWSER" > "$HOME/.urlview" - return 0 + info="$(curl --location-trusted -s -m 5 --user "$login:$(pass "$passprefix$fulladdr")" --url "${protocol:-imaps}://$imap:${iport:-993}")" + [ -z "$info" ] && echo "Log-on not successful." && return 1 + mailboxes="$(echo "$info" | grep -v HasChildren | sed "s/.*\" //;s/\"//g" | tr -d '\r')" + fi + [ "$type" = "pop" ] && mailboxes="INBOX" + for x in $(sed -n "/^macro.* i[0-9] / s/\(^macro.* i\| .*\)//gp " "$muttrc" 2>/dev/null | sort -u; echo 0); do + idnum=$((idnum + 1)) + [ "$idnum" -eq "$x" ] || break + done + toappend="mailboxes $(echo "$mailboxes" | sed "s/^/\"=/;s/$/\"/" | paste -sd ' ' - )" } -confirm() { printf "Do you want to %s? [yes/N]\\n\t" "$@" && read -r input && ! echo "$input" | grep -i "^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 "^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 +finalize() { echo "$toappend" >> "$accdir/$fulladdr.muttrc" + [ "$type" != "online" ] && echo "$mailboxes" | xargs -I {} mkdir -p "$maildir/$fulladdr/{}/cur" "$maildir/$fulladdr/{}/tmp" "$maildir/$fulladdr/{}/new" + echo "$fulladdr (account #$idnum) added successfully." + command -V urlview >/dev/null 2>&1 && [ ! -f "$HOME/.urlview" ] && echo "COMMAND \$BROWSER" > "$HOME/.urlview" 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 - } - -choosecron() { ! pgrep cron >/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 * * * * $(type mailsync | cut -d' ' -f3) >/dev/null 2>&1") | crontab - >/dev/null && - 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 ;} - -purge() { confirm "delete all account data" || exit - rm -rf "$mbsyncrc" "$accdir" "$HOME/.config/msmtp" "$cachedir" - crontab -l | sed '/mailsync/d' | crontab - >/dev/null - echo "All configs and account settings have been purged." - sed -ibu "/\# mw-autogenerated/d" "$muttrc" ; rm -f "$muttrc"bu -} - -notmuchauto() { \ +prepnotmuch() { \ [ -z "$NOTMUCH_CONFIG" ] && NOTMUCH_CONFIG="$HOME/.notmuch-config" [ -f "$NOTMUCH_CONFIG" ] && return 0 - nmbasic="[database] + echo "[database] path=$maildir [user] name=$realname @@ -339,31 +254,118 @@ 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 - -case "$1" in - 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 +gpg_path=$GPG" > "$NOTMUCH_CONFIG" ;} + +togglecron() { cron="$(mktemp)" + crontab -l > "$cron" + if grep -q mailsync "$cron"; then + echo "Removing automatic mailsync..." + sed -ibu /mailsync/d "$cron"; rm -f "$cron"bu + else + echo "Adding automatic mailsync every ${cronmin:-10} minutes..." + echo "*/${cronmin:-10} * * * * $prefix/bin/mailsync -q" >> "$cron" + fi && + crontab "$cron"; rm -f "$cron" ;} + +setact() { 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; } + +mwinfo() { cat << EOF mw: mutt-wizard, auto-configure email accounts for mutt including downloadable mail with \`isync\`. -Allowed options: - 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 +Main actions: + -a your@email.com Add an email address + -l List email addresses configured + -d Remove an already added address + -D your@email.com Force remove account without confirmation + -y your@email.com Sync mail for account by name + -Y Sync mail for all accounts + -t number Toggle automatic mailsync every <number> minutes + -T Toggle automatic mailsync + -r Reorder account numbers + +Options allowed with -a: + -u Account login name if not full address + -n "Real name" to be on the email account + -i IMAP/POP server address + -I IMAP/POP server port + -s SMTP server address + -S SMTP server port + -x Password for account (recommended to be in double quotes) + -P Pass Prefix (prefix of the file where password is stored) + -p Add for a POP server instead of IMAP. + -X Delete an account's local email too when deleting. + -o Configure address, but keep mail online. + -f 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. + +To change an account's password, run \`pass edit '$passprefix'your@email.com\`. EOF +} + +reorder() { + tempfile="$(mktemp -u)" + trap 'rm -f $tempfile' HUP INT QUIT TERM PWR EXIT + echo "# Carefully reorder these accounts with the desired numbers in the first column. +# DO NOT reorder rows or rename the accounts in the second column." > "$tempfile" + sed -n " + / i[0-9] / s?\(.* i\|'<sync.*/\|\.muttrc.*\)??g p + " "$muttrc" >> "$tempfile" + ${EDITOR:-vim} "$tempfile" || exit 1 + sed -i -e 's/#.*//' -e '/^$/d' "$tempfile" + default="$(sort -n "$tempfile" | head -n 1)" + default="${default#* }" + sed -ibu " + /.* i[0-9] .*.muttrc/d + /^source.*accounts.*.muttrc/d + " "$muttrc" 2>/dev/null; rm -f "$muttrc"bu + awk -v a="$accdir" -v d="$default" ' BEGIN { print "source "a"/"d".muttrc" } + { + print "macro index,pager i"$1" '\''<sync-mailbox><enter-command>source "a"/"$2".muttrc<enter><change-folder>!<enter>;<check-stats>'\'' \"switch to "$2"\"" + } + ' "$tempfile" >> "$muttrc" +} + +while getopts "rfpXlhodTYD:y:i:I:s:S:u:a:n:P:x:m:t:" o; do case "${o}" in + l) setact list || exit 1 ;; + r) setact reorder || exit 1 ;; + d) setact delete || exit 1 ;; + D) setact delete || exit 1 ; fulladdr="$OPTARG" ;; + y) setact sync || exit 1 ; fulladdr="$OPTARG" ;; + Y) setact sync || exit 1 ;; + a) setact add || exit 1 ; fulladdr="$OPTARG" ;; + i) setact add || exit 1 ; imap="$OPTARG" ;; + I) setact add || exit 1 ; iport="$OPTARG" ;; + s) setact add || exit 1 ; smtp="$OPTARG" ;; + S) setact add || exit 1 ; sport="$OPTARG" ;; + u) setact add || exit 1 ; login="$OPTARG" ;; + n) setact add || exit 1 ; realname="$OPTARG" ;; + P) setact add || exit 1 ; passprefix="$OPTARG" ;; + m) setact add || exit 1 ; maxmes="$OPTARG" ;; + o) setact add || exit 1 ; type="online" ;; + p) setact add || exit 1 ; type="pop"; protocol="pop3s" ; iport="${iport:-995}" ;; + f) setact add || exit 1 ; force=True ;; + x) setact add || exit 1 ; password="$OPTARG" ;; + X) setact delete || exit 1 ; purge=True ;; + t) setact toggle || exit 1 ; cronmin="$OPTARG" ;; + T) setact toggle || exit 1 ;; + *) mwinfo; exit 1 ;; +esac done + +case "$action" in + list) list ;; + add) checkbasics && askinfo && getboxes && getprofiles && finalize ;; + delete) delete ;; + sync) mailsync $fulladdr ;; + toggle) togglecron ;; + reorder) reorder ;; + *) mwinfo; exit 1 ;; esac diff --git a/bin/openfile b/bin/openfile deleted file mode 100755 index f6668dc..0000000 --- a/bin/openfile +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh - -# Helps open a file with xdg-open from mutt in a external program without weird side effects. -[ "$(uname)" = "Darwin" ] && opener="open" || opener="setsid xdg-open" -mkdir -p "/tmp/$USER-mutt-tmp" -file="/tmp/$USER-mutt-tmp/$(basename "$1")" -rm -f "$file" -cp "$1" "$file" -$opener "$file" >/dev/null 2>&1 & |