#!/bin/bash

info_file=$1

# the email address info file for user that will be used
# the file content may in a standard format, for example:
# ---
#       EMAIL_ADDR=zhangsan@compass-ci.org
#       EMAIL_PASS={{ email passwd }}
#       EMAIL_NAME="Zhang San"
#       EMAIL_SMTP_URL="smtps://zhangsan\@compass-ci.org@smtp.exmail.qq.com:465"
#       MAIL_DIR="~/Maildir"
#       MAIL_BOX="inbox"
# ---

[[ -n $info_file ]] || {
        echo "add info_file for email config"
        exit 1
}

source $info_file

# when redo the email configration, backup the old config files
[[ -f $HOME/.mutt/${MAIL_BOX}.muttrc ]] && {
        mv $HOME/.mutt/${MAIL_BOX}.muttrc $HOME/.mutt/${MAIL_BOX}.muttrc.bk
}

[[ -f $HOME/.procmailrc ]] && {
        mv $HOME/.procmailrc $HOME/.procmailrc.bk
}

[[ -f $HOME/.fetchmailrc ]] && {
        mv $HOME/.fetchmailrc $HOME/.fetchmailrc.bk
}

# kill the old process before redo the config 
fetchmail_pid=$(ps -ef | grep fetchmail | grep -v grep | grep $USER | awk '{print $2}')
[[ -n $fetchmail_pid ]] && kill -9 $fetchmail_pid

# build standard mailbox directories
[[ -d ${MAIL_DIR}/.${MAIL_BOX} ]] || {
        mkdir -p ${MAIL_DIR}/.${MAIL_BOX}/new
        mkdir -p ${MAIL_DIR}/.${MAIL_BOX}/cur
        mkdir -p ${MAIL_DIR}/.${MAIL_BOX}/tmp
}

[[ -d ${MAIL_DIR}/log ]] || {
        mkdir -p ${MAIL_DIR}/log
}

# add config for procmail
# case you have multi mailboxes to config, add config as below:
# all emails to {{ EMAIL_ADDR }} will be stored to .inbox/
# ---
#       :0:
#       * ^To:.{{ EMAIL_ADDR }}
#       .{{ MAIL_BOX }}/
# ---
cat >> $HOME/.procmailrc <<-EOF
	VERBOSE=off
	MAILDIR=${MAIL_DIR}
	LOGFILE=${MAIL_DIR}/log/procmail

	:0:
	* ^To:.*crystal.ci
	.inbox/

	:0:
	* ^To:.*compass-ci.org
	.${MAIL_BOX}/

	:0:
	.inbox/
EOF

# add config for fetchmail
cat >> $HOME/.fetchmailrc <<-EOF
	poll imap.exmail.qq.com with proto IMAP
	username "${EMAIL_ADDR}"
	password "${EMAIL_PASS}"
	mda "/usr/bin/procmail -f %F -d %T"
	nokeep
EOF

# add config for mutt
[[ -d $HOME/.mutt ]] || mkdir -p $HOME/.mutt

cat >> $HOME/.mutt/${MAIL_BOX}.muttrc <<-EOF
	set ssl_starttls=yes
	set ssl_force_tls=yes
	set ssl_use_sslv3=yes
	set timeout=60
	set smtp_authenticators="login"
	set realname="${EMAIL_NAME}"
	set from="${EMAIL_ADDR}"
	set smtp_url="${EMAIL_SMTP_URL}"
	set smtp_pass="${EMAIL_PASS}"

	set mbox_type=Maildir
	set folder="~/Maildir"
	set mbox="~/Maildir/.${MAIL_BOX}"
	set spoolfile="~/Maildir/.${MAIL_BOX}"

	source /etc/mutt/aliases.muttrc.cf
EOF

chmod 700 $HOME/.fetchmailrc $HOME/.procmailrc

# start fetchmail process immediately.
fetchmail -d 60

# add crontab jobs to start fetchmail at server's per reboot for users.
( crontab -l | grep -v "@reboot fetchmail -d 60"; echo "@reboot fetchmail -d 60" ) | crontab -
