#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
. gettext.sh
TEXTDOMAIN="elive-tools"
export TEXTDOMAIN

tempfile_tmp="/tmp/.${USER}-$(basename $0)_tmp_$$"
tempfile_body="/tmp/.${USER}-$(basename $0)_body_$$"
el_add_on_exit rm -f "$tempfile_tmp" "$tempfile_body"

#===  FUNCTION  ================================================================
#          NAME:  do_email_send
#   DESCRIPTION:  send of email
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
do_email_send(){
    # pre {{{

    if ! el_dependencies_check "mutt" ; then
        el_dependencies_install "mutt|libsasl2-modules|ca-certificates"
    fi

    # check if we have a valid setup and otherwise set it up first
    if [[ -z "$email_account" ]] || [[ -z "$email_password" ]] || ! [[ -s "$conf_mutt" ]] ; then
        do_configure
        do_validate_sending
    fi


    if ! el_check_variables "conf_mutt|conf" ; then
        do_configure
    fi

    if ! el_check_variables "to" ; then
        el_error "missing arguments"
        exit 1
    fi

    if test -s "$message" 1>/dev/null 2>/dev/null ; then
        is_message_file=1
    fi

    # }}}

    if ((is_message_file)) ; then
        if file "$message" | grep -qsi "HTML Document" ; then
            is_html=1
        fi
    fi

    # forced plain mode?
    if ((is_plain_mode)) ; then
        unset is_html
    fi

    #
    # Default values
    #
    username="$(awk -v FS=":" -v user="$USER" '{if ($1 == user) print $5 }' /etc/passwd | sed -e 's|,.*$||g' | tail -1 )"
    if [[ -z "$username" ]] || echo "$username" | grep -qsiE "Elive.User" ; then
        username="$USER"
    fi
    # upcase it
    username="$(echo "$username" | sed 's/[^ _-]*/\u&/g' )"

    if [[ -z "$subject" ]] ; then
        local message_subject
        message_subject="$( printf "$( eval_gettext "A message from %s on %s's supercomputer" )" "$username" "$(hostname | sed 's/[^ _-]*/\u&/g' )" )"

        subject="$message_subject"
    fi

    if [[ -z "$template" ]] ; then
        template="default"
    fi

    if [[ -n "$title" ]] ; then
        if [[ "${template}" = "none" ]] ; then
            el_warning "You have set a title but template $template doesn't supports it (use 'plain' instead?)"
        fi
    else
        title="$subject"
    fi

    # User on Hostname (default headertext)
    if [[ -z "$headertext" ]] ; then
        headertext="$( echo "${username} on $(hostname | sed 's/[^ _-]*/\u&/g' )" )"
    fi

    # default message if no messages
    if ! el_check_variables "message" 1>/dev/null 2>/dev/null ; then

        if [[ -n "${attachments[@]}" ]] ; then
            local message_message_default
            message_message_default="$( printf "$( eval_gettext "Check the attached files." )" )"

            message="$message_message_default"

        else
            el_error "missing arguments: message"
            exit 1
        fi
    fi


    #
    # Prepare body message:
    #
    if ((is_plain_mode)) ; then
        # dump to file and dont do any html conversion
        if ((is_message_file)) ; then
            cp -f "$message" "$tempfile_body"
        else
            echo "$message" > "$tempfile_body"
        fi
    else
        # we don't want to be strictly plain, so let's do the conversion
        if ! ((is_stdin)) ; then
            # if is stdin we have already it
            if ((is_message_file)) ; then
                cp -f "$message" "$tempfile_tmp"
            else
                echo "$message" > "$tempfile_tmp"
            fi
        fi

        # set template
        if [[ -f "/usr/share/email-sender/templates/$template/header.html" ]] ; then
            template_header="/usr/share/email-sender/templates/$template/header.html"
            template_footer="/usr/share/email-sender/templates/$template/footer.html"
        else
            el_error "template don't exist in /usr/share/email-sender/templates"
        fi


        # if we are not html (file command) we should convert it to html first
        if ((is_html)) ; then
            cp -f "$tempfile_tmp" "$tempfile_body"
        else
            # translate some simple text to html
            cat "$tempfile_tmp" | awk '{if ($0 ~ /^\s+/)  print "<pre>"$0"</pre>"; else  print $0"<br/>" }' > "$tempfile_body"
            is_html=1
        fi
    fi


    #
    # Send !
    #

    if ((is_html)) ; then

        # create body
        cp -f "$tempfile_body" "$tempfile_tmp"
        cat "$template_header" "$tempfile_tmp" "$template_footer" | sed \
            -e "s|XXXyearXXX|$(date +%Y)|g" \
            -e "s|XXXusernameXXX|$username|g" \
            -e "s|XXXyearXXX|$(date +%Y)|g" \
            -e "s|XXXhostnameXXX|$(hostname | sed 's/[^ _-]*/\u&/g' )|g" \
            -e "s|XXXheadertextXXX|${headertext}|g" \
            -e "s|XXXyearXXX|$(date +%Y)|g" \
            -e "s|XXXtitleXXX|$title|g" \
            -e "s|XXXsubjectXXX|$subject|g" \
            > "$tempfile_body"

        # SEND !
        cat "$tempfile_body" | LC_ALL="$EL_LC_EN" timeout 60 mutt -F "$conf_mutt" -s "$subject" "$to" -e 'set content_type="text/html"' "${attachments[@]/#/-a}" "${targets_cc[@]/#/-c}" "${targets_bcc[@]/#/-b}" --
        if [[ "$?" = 0 ]] ; then
            if ! ((is_mode_quiet)) ; then
                el_explain 2 "email sent"
            fi
        else
            # try again
            cat "$tempfile_body" | LC_ALL="$EL_LC_EN" timeout 120 mutt -F "$conf_mutt" -s "$subject" "$to" -e 'set content_type="text/html"' "${attachments[@]/#/-a}" "${targets_cc[@]/#/-c}" "${targets_bcc[@]/#/-b}" --

            if [[ "$?" = 0 ]] ; then
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "email sent"
                fi
            else
                el_warning "unable to send email, let's wait 2 minutes and we will try again"
                sleep 120
                # try again
                cat "$tempfile_body" | LC_ALL="$EL_LC_EN" timeout 120 mutt -F "$conf_mutt" -s "$subject" "$to" -e 'set content_type="text/html"' "${attachments[@]/#/-a}" "${targets_cc[@]/#/-c}" "${targets_bcc[@]/#/-b}" --

                if [[ "$?" = 0 ]] ; then
                    if ! ((is_mode_quiet)) ; then
                        el_explain 2 "email sent"
                    fi
                else
                    # reconfigure or exit {{{
                    local message_reconfigure
                    message_reconfigure="$( printf "$( eval_gettext "We have a problem sending email. Reconfigure it?" )" "" )"

                    if ! $guitool --question --text="$message_reconfigure" ; then
                        # we don't want to reconfigure, so just exit
                        el_error "unable to send email, run again the tool or reconfigure your account"
                        exit 0
                    fi

                    # }}}
                    is_message_showed_welcome=1
                    do_configure
                    do_validate_sending
                    # send again -this- email
                    $FUNCNAME
                fi
            fi
        fi

    else

        # SEND !
        cat "$tempfile_body" | LC_ALL="$EL_LC_EN" timeout 60 mutt -F "$conf_mutt" -s "$subject" "$to" "${attachments[@]/#/-a}" "${targets_cc[@]/#/-c}" "${targets_bcc[@]/#/-b}" --

        if [[ "$?" = 0 ]] ; then
            if ! ((is_mode_quiet)) ; then
                el_explain 2 "email sent"
            fi
        else
            # try again
            cat "$tempfile_body" | LC_ALL="$EL_LC_EN" timeout 120 mutt -F "$conf_mutt" -s "$subject" "$to" "${attachments[@]/#/-a}" "${targets_cc[@]/#/-c}" "${targets_bcc[@]/#/-b}" --

            if [[ "$?" = 0 ]] ; then
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "email sent"
                fi
            else
                el_warning "unable to send email, let's wait 2 minutes and we will try again"
                sleep 120
                # try again
                cat "$tempfile_body" | LC_ALL="$EL_LC_EN" timeout 120 mutt -F "$conf_mutt" -s "$subject" "$to" "${attachments[@]/#/-a}" "${targets_cc[@]/#/-c}" "${targets_bcc[@]/#/-b}" --

                if [[ "$?" = 0 ]] ; then
                    if ! ((is_mode_quiet)) ; then
                        el_explain 2 "email sent"
                    fi
                else
                    # reconfigure or exit {{{
                    local message_reconfigure
                    message_reconfigure="$( printf "$( eval_gettext "We have a problem sending email. Reconfigure it?" )" "" )"

                    if ! $guitool --question --text="$message_reconfigure" ; then
                        # we don't want to reconfigure, so just exit
                        el_error "unable to send email, run again the tool or reconfigure your account"
                        exit 0
                    fi

                    # }}}
                    is_message_showed_welcome=1
                    do_configure
                    do_validate_sending
                    # send again -this- email
                    $FUNCNAME
                fi
            fi
        fi
    fi

}
#===  FUNCTION  ================================================================
#          NAME:  do_validate_sending
#   DESCRIPTION:  validate if our set up email really works
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
do_validate_sending(){
    # pre {{{
    local result
    el_check_files "$conf_mutt"

    if ! el_dependencies_check "mutt" ; then
        el_dependencies_install "mutt|libsasl2-modules|ca-certificates"
    fi

    if ! el_dependencies_check "curl" ; then
        el_dependencies_install "curl"
    fi

    # seems like we need this package in order to send emails from gmail
    if [[ ! -d "/usr/share/doc/libsasl2-modules" ]] ; then
        el_dependencies_install "libsasl2-modules"
    fi
    if [[ ! -d "/usr/share/doc/ca-certificates" ]] ; then
        el_dependencies_install "libsasl2-modules"
    fi

    if [[ -z "$random" ]] ; then
        random="$RANDOM$RANDOM$RANDOM"
        random="${RANDOM:0:8}"
    fi

    # }}}

    if ! echo "This is a verification email send by your own computer, seems like it works so just delete or ignore me" | mutt -F "$conf_mutt" -s "testing elive email ($random)" "$email_account" ; then
        $guitool --error --text="$( eval_gettext "Seems like there was a problem sending a test email. Please verify your settings." )"
    fi
    #sleep 2


    case "$email_account_type" in
        Dreamhost)
            $guitool --info --text="$( eval_gettext "Open your email client and check that you have a test email in your inbox. Proceed once you have verified this." )"
            if $guitool --question --text="$( eval_gettext "Does the sending of emails work correctly?" )" ; then
                # save our conf because we know that it works now
                rm -f "$conf" 2>/dev/null
                echo "email_account=\"$email_account\"" >> "$conf"
                echo "email_password=\"$email_password\"" >> "$conf"
                echo "# References that needs to be updated: $HOME/.mutt/accounts/elive-sender" >> "$conf"

                chmod og-rwx "${conf}"

                $guitool --info --text="$( eval_gettext "Ready! You can start using the tool now" )"
                return 0
            else
                $guitool --error --text="$( eval_gettext "Unable to configure your email. Try with a different provider?" )"
                return 1
            fi
            ;;

        *@gmail*|Gmail)
            for i in 1 2 3 4 5 6 7
            do
                result="$( curl -u "${email_account}:${email_password}" --silent "https://mail.google.com/mail/u/0/feed/atom" | sed -e 's|<entry>|\n\n<entry>|g' | grep "<entry>" | sed -e 's|^.*<title>||g' -e 's|</title>.*$||g' | head -3 )"

                if echo "$result" | grep -qs "testing elive email ($random)" ; then
                    # succeed
                    local message_success_sending
                    message_success_sending="$( printf "$( eval_gettext "Email configuration is working correctly: you will find a test email in your account. You can safely delete it." )" "" )"

                    if ! { [[ -s "$conf" ]] && grep -qs "email_password=" "$conf" ; } ; then
                        $guitool --info --text="$message_success_sending" || true
                    fi

                    # save our conf because we know that it works now
                    rm -f "$conf" 2>/dev/null
                    echo "email_account=\"$email_account\"" >> "$conf"
                    echo "email_password=\"$email_password\"" >> "$conf"
                    echo "# References that needs to be updated: $HOME/.mutt/accounts/elive-sender" >> "$conf"

                    chmod og-rwx "${conf}"

                    return 0
                else
                    sleep 1
                fi

            done
            ;;
        *)
            if $guitool --question --text="$( eval_gettext "Does sending emails work correctly?" )" ; then
                # save our conf because we know that it works now
                rm -f "$conf" 2>/dev/null
                echo "email_account=\"$email_account\"" >> "$conf"
                echo "email_password=\"$email_password\"" >> "$conf"
                echo "# References that needs to be updated: $HOME/.mutt/accounts/elive-sender" >> "$conf"

                chmod og-rwx "${conf}"

                $guitool --info --text="$( eval_gettext "Ready! You can start using the tool now" )"
                return 0
            fi
            ;;
    esac


    # it was correctly configured previously
    if grep -qs "^email_password=" "$conf" ; then
        local message_reconfigure
        message_reconfigure="$( printf "$( eval_gettext "We have a problem sending email. Reconfigure it?" )" "" )"

        if ! $guitool --question --text="$message_reconfigure" ; then
            # we don't want to reconfigure, so just exit
            return 0
        fi
    else

        # it was not configured correctly before, so proceed normally with configuration
        local message_cannot_send_email
        message_cannot_send_email="$( printf "$( eval_gettext "Seems like we cannot send or read emails from this account. Are your username and password correctly set? You also need to have the POP and IMAP options activated in your email settings." )" "" )"
        $guitool --warning --text="$message_cannot_send_email"

    fi

    # configure pop / imap?
    local message_popimap
    message_popimap="$( printf "$( eval_gettext "Do you want to configure the POP and IMAP options in your Gmail account now? You need to enable them." )" )"
    if $guitool --question --text="$message_popimap" ; then
        /etc/alternatives/x-www-browser "https://mail.google.com/mail/u/0/#settings/fwdandpop" &
        sleep 25
    fi

    # configure less-secure apps
    /etc/alternatives/x-www-browser "https://myaccount.google.com/u/0/signinoptions/two-step-verification/enroll-welcome" &
    sleep 3
    local message_lesssecure
    message_lesssecure="$( printf "$( eval_gettext "First, enable 2-step verification in your Google account." )" )"
    $guitool --info --text="$message_lesssecure"

    # configure less-secure apps (more)
    /etc/alternatives/x-www-browser "https://myaccount.google.com/u/0/apppasswords" &
    sleep 3
    local message_app_password
    message_app_password="$( printf "$( eval_gettext "Now you need to create a special password in Gmail to use with this tool. Where it says to select an App, pick the 'Email' option. And then where it says to select a device, pick the 'Other' option. Save the given password, which is the one to use with this tool." )" )"

    $guitool --info --text="$message_app_password"


    local message_try_again
    message_try_again="$( printf "$( eval_gettext "Do you want to change the email or password that you have previously inserted?" )" )"
    local message_try_or_exit
    message_try_or_exit="$( printf "$( eval_gettext "Try again?" )" )"
    local message_error_configuring_email
    message_error_configuring_email="$( printf "$( eval_gettext "We cannot configure mutt for this account. Try running it manually with the command:" )" "  cd ~/.mutt/accounts ; mutt -F elive-sender" )"



    # change user and pass?
    if $guitool --question --text="$message_try_again" ; then
        unset email_account email_password
    else
        # just ask if we want to continue
        if $guitool --question --text="$message_try_or_exit" ; then
            return 0
        else

            $guitool --error --text="$message_error_configuring_email"
            exit 1
        fi
    fi




    # so try again
    do_configure
    do_validate_sending
}

#===  FUNCTION  ================================================================
#          NAME:  do_configure
#   DESCRIPTION:  configure email client
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
do_configure(){
    # pre {{{

    if ((is_configure_force)) ; then
        unset email_account email_password
    else
        # email was already set and working, so do not configure it again
        if [[ -s "$conf" ]] && grep -qs "email_password=" "$conf" ; then
            el_explain 2 "email was already configured and working, skipping to reconfigure it"
            source "$conf"
            return 0
        fi

    fi

    # }}}
    if [[ -z "$email_account" ]] ; then
        local message_intro
        message_intro="$( printf "$( eval_gettext "To send emails, you need to configure it first. Do you want to do it now?" )" "" )"

        if ! ((is_message_showed_welcome)) ; then
            if $guitool --question --text="$message_intro" ; then
                is_message_showed_welcome=1
            else
                el_error "You didn't want to set up your email sending? ok..."
                exit 1
            fi
        fi

        local message_email_service
        message_email_service="$( printf "$( eval_gettext "Which email provider you want to use?" )" "" )"

        email_account_type="$( echo -e "Gmail\nSMTP\nDreamhost\nother" | $guitool --list --column="Provider" --text="$message_email_service" || echo cancel )"

        case "$email_account_type" in
            cancel)
                $guitool --error
                exit 1
                ;;
            other)
                # TODO: implement a questions asking about the stmp / imap / ports addresses, all of them needed, it should simply work
                $guitool --info --text="$( eval_gettext "This tool only supports (for now) the listed services available; if you want to use a different one, you can improve the tool on our Git to include the needed configuration for your service. Exiting..." )"
                exit
                ;;
            Gmail)
                $guitool --warning --text="$( eval_gettext "There have been some difficulties trying to use Gmail recently. We hope you can manage to make it working with detailed instructions. You are welcome to improve this tool to support other services too, by simply including the needed configurations" )"
                ;;
            *)
                true
                ;;
        esac


        local message_login
        message_login="$( printf "$( eval_gettext "Insert the email to use, for example: %s" )" "john.smith@gmail.com" )"

        # request username
        email_account="$( $guitool --entry --text="$message_login" || echo cancel )"


        local message_invalid
        #message_invalid="$( printf "$( eval_gettext "Invalid entry, you need to use use a Gmail account, for example '%s', try again." )" "john.smith@gmail.com" )"
        message_invalid="$( printf "$( eval_gettext "Invalid entry, please use an account from the listed services, for example '%s'. Try again." )" "john.smith@gmail.com" )"

        # verify username inserted
        #if [[ "${email_account}" = "cancel" ]] || ! echo "$email_account" | grep -qs "@gmail." || ! echo "$email_account" | grep -qs "@gmail." ; then
        if [[ "${email_account}" = "cancel" ]] ; then
            $guitool --error --text="$message_invalid"

            email_account="$( $guitool --entry --text="$message_invalid" || echo cancel )"

            #if [[ "${email_account}" = "cancel" ]] || ! echo "$email_account" | grep -qs "@gmail." || ! echo "$email_account" | grep -qs "@gmail." ; then
            if [[ "${email_account}" = "cancel" ]] ; then
                exit 1
            fi
        fi
    fi


    # request password too
    if [[ -z "$email_password" ]] ; then
        local message_password
        message_password="$( printf "$( eval_gettext "Insert the email password" )" "" )"

        email_password="$( $guitool --entry --text="$message_password" || echo cancel )"

        if [[ "${email_password}" = "cancel" ]] ; then
            email_password="$( $guitool --entry --text="$message_password" || echo cancel )"

            if [[ "${email_password}" = "cancel" ]] ; then
                exit 1
            fi
        fi
    fi

    case "$email_account_type" in
        SMTP)
            local message_ask_smtp_url
            message_ask_smtp_url="$( printf "$( eval_gettext "Insert the URL for your SMTP connection." )" "" )"
            smtp_url="$( $guitool --entry --entry-text="smtp.yourdomain.com" --text="$message_ask_smtp_url" || echo "" )"

            local message_ask_smtp_port
            message_ask_smtp_port="$( printf "$( eval_gettext "Insert the port to connect to your SMTP. The most common ones are 587, 465, 25." )" "" )"
            smtp_port="$( $guitool --entry --entry-text="587" --text="$message_ask_smtp_port" || echo "" )"

            local message_ask_imap_url
            message_ask_imap_url="$( printf "$( eval_gettext "Insert the IMAP address to check your email." )" "" )"
            imap_url="$( $guitool --entry --entry-text="mail.yourdomain.com" --text="$message_ask_imap_url" || echo "" )"

            if [[ -z "$smtp_url" ]] || [[ -z "$smtp_port" ]] || [[ -z "$imap_url" ]] ; then
                $guitool --error --text="$( eval_gettext "Missing values. Aborting..." )"
                exit 1
            fi
            ;;
    esac

    # cleanups
    rm -f "$conf"
    mkdir -p "$(dirname "$conf_mutt" )"
    rm -f "$conf_mutt"


    # configure client
    case "$email_account_type" in
        *@gmail*|Gmail)
            echo "# stmp, sending of emails:" >> "${conf_mutt}"
            echo "set smtp_url = \"smtp://${email_account%%@*}@smtp.gmail.com:587/\"" >> "${conf_mutt}"
            echo "set smtp_pass = \"${email_password}\"" >> "${conf_mutt}"
            echo "set imap_user = \"${email_account%%@*}\"" >> "${conf_mutt}"
            echo "set imap_pass = \"${email_password}\"" >> "${conf_mutt}"
            echo "#set imap_passive = no" >> "${conf_mutt}"
            echo "set from = \"${email_account%%@*}\"" >> "${conf_mutt}"
            echo "set spoolfile = \"imaps://imap.gmail.com:993/INBOX\"" >> "${conf_mutt}"
            echo "set folder = \"imaps://imap.gmail.com:993\"" >> "${conf_mutt}"
            echo "#set record = \"+[Gmail]/Sent Mail\"" >> "${conf_mutt}"
            echo "#set postponed = \"+[Gmail]/Drafts\"" >> "${conf_mutt}"
            echo "set realname = \"${USER} from $(hostname) - Elive\"" >> "${conf_mutt}"
            echo "set copy = no" >> "${conf_mutt}"
            echo "set move = no" >> "${conf_mutt}"
            echo "set timeout = 120" >> "${conf_mutt}"

            chmod og-rwx "${conf_mutt}"

            ;;
        SMTP)
            cat > "${conf_mutt}" << EOF
# stmp, sending of emails:
set smtp_url = "smtp://${email_account}@${smtp_url}:${smtp_port}/"
set smtp_pass = "${email_password}"
set from = "${USER}@${email_account#*@}"
set realname = "${USER} from $(hostname) - Elive"
set copy = no
set timeout = 120

set imap_user="${email_account}"
set imap_pass="${email_password}"
set from="${email_account}"
set spoolfile=imaps://${imap_url}/
set folder=imaps://${imap_url}/INBOX/
set record="=Sent"
set postponed ="=Drafts"
set mail_check=60 # So mutt doesn’t keep checking your IMAP folders like a chihuahua with ADHD
set imap_keepalive = 10 # You may find a small number (like 10) is required to avoid TLS socket packet

set ssl_force_tls=yes
EOF
            ;;
        Dreamhost)
            cat > "${conf_mutt}" << EOF
# stmp, sending of emails:
set smtp_url = "smtp://${email_account}@smtp.dreamhost.com:587/"
set smtp_pass = "${email_password}"
set from = "${USER}@${email_account#*@}"
set realname = "${USER} from $(hostname) - Elive"
set copy = no
set timeout = 120

set imap_user="${email_account}"
set imap_pass="${email_password}"
set from="${email_account}"
set spoolfile=imaps://mail.${email_account##*@}/
set folder=imaps://mail.${email_account##*@}/INBOX/
set record="=Sent"
set postponed ="=Drafts"
set mail_check=60 # So mutt doesn’t keep checking your IMAP folders like a chihuahua with ADHD
set imap_keepalive = 10 # You may find a small number (like 10) is required to avoid TLS socket packet

set ssl_force_tls=yes
EOF
            ;;
        #*@yahoo*)
            # Well, we don't know how to verify if the sending works from a yahoo one so let's disable it for now
            #echo "# stmp, sending of emails:" >> "${conf_mutt}"
            #echo "set smtp_url = \"smtp://smtp.mail.${email_yahoo##*@}:587/\"" >> "${conf_mutt}"
            #echo "set from = \"${email_account}\"" >> "${conf_mutt}"
            #echo "set smtp_pass = \"${email_password}\"" >> "${conf_mutt}"

            #echo "email_account=\"$email_account\"" >> "$conf"
            #echo "email_password=\"$email_password\"" >> "$conf"
            #echo "# References that needs to be updated: $HOME/.mutt/accounts/elive-sender" >> "$conf"
            #;;

        *)
            $guitool --error --text="Unknown email service provider, you should use a gmail account"
            ;;
    esac

    # make it default if we have not another config previously
    if [[ ! -e "$HOME/.muttrc" ]] ; then
        ln -s "$conf_mutt" "$HOME/.muttrc"
    fi

}

#===  FUNCTION  ================================================================
#          NAME:  usage
#   DESCRIPTION:  shows usage help
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
usage(){
    echo -e "
    Usage: $(basename $0) args:

[sending options]:
-a attach_file (can be called multiple times, optional)
-t to
-x CC: (extra recipients in CC form)
-X BCC: (extra recipients in blind-CC form)
-s subject (optional) - second line in phone notifications
-H header-text (defaults to: \$user on \$hostname) - preview in gmail list
-S super-subject (title for the message body, optional)
-m message (can be file or text passed)
-T template to use (if you want to use, optional) [default|none]

[other options]
-c  configure: it sets up your email sending and then exits
-C  check:  checks if your sending of email works, and exits
-d  debug mode
-v  verbose mode
-q  quiet mode

[environmental variables]
REPLYTO

[modes]
- You can use this tool with -m 'message' or concatenating from the standard input
"

    exit

}

main(){
    # pre {{{
    local conf

    # user conf
    conf="$HOME/.config/email-sender"
    conf_mutt="$HOME/.mutt/accounts/elive-sender"

    if [[ -s "$conf" ]] ; then
        source "$conf"
    fi

    if [[ ! -t 0 ]] ; then
        is_stdin=1
    fi

    # do not fill /tmp with visual trash
    TMPDIR="/tmp/.$(basename $0)-${USER}"
    mkdir -p "$TMPDIR"
    export TMPDIR

    if ! el_verify_internet 2>/dev/null ; then
        el_error "$(basename $0): You need to be connected to internet in order to send emails"
        exit 1
    fi

    # }}}

    # Usage
    if [[ -z "${1}" ]] ; then
        usage
    fi


    while getopts ":a:cCdhm:s:S:H:pt:T:vqx:X:" opt; do
        case "$opt" in
            a)
                el_array_member_add "$OPTARG" "${attachments[@]}" ; attachments=("${_out[@]}")
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "attached file: $OPTARG"
                fi

                ;;
            c)
                el_debug "configure mode"
                is_configure_force=1
                do_configure
                do_validate_sending
                exit

                ;;
            C)
                do_validate_sending
                exit

                ;;
            d)
                export EL_DEBUG=3

                ;;
            h)
                usage
                exit
                ;;

            p)
                is_plain_mode=1
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "__plain__ mode selected"
                fi

                ;;
            m)
                # note: if you are trying to pass an array full of contents to the message, there's no bug on it, you should pass like: email-sender -m "${arr[*]}", instead of using @
                message="$OPTARG"
                message_excerpt="${message:0:300}"

                if ! ((is_mode_quiet)) ; then
                    if [[ "$( echo "$message" | wc -m )" -lt 300 ]] ; then
                        el_explain 2 "message is __${message} ... (cut)__"
                    else
                        el_explain 2 "message is __${message_excerpt} ... (cut)__"
                    fi
                fi
                # sometimetimes the stdin detection can fail, but if we have the message parameter is for sure that we don't want the stdin input, so we are defining it
                unset is_stdin

                ;;
            s)
                subject="$OPTARG"
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "subject is __${subject}__"
                fi

                ;;
            S)
                title="$OPTARG"
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "Title is __${title}__"
                fi

                ;;
            H)
                headertext="$OPTARG"
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "Headertext is __${headertext}__"
                fi

                ;;
            t)
                to="$OPTARG"

                # check / validate, or we will have delivery errors
                if ! echo "$to" | grep -qs "@.*\." ; then
                    el_error "to: '$to' is not a valid email"
                    exit 1
                fi

                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "target (to) is __${to}__"
                fi

                ;;
            T)
                template="$OPTARG"
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "template is __${template}__"
                fi

                ;;
            v)
                export EL_DEBUG=2

                ;;
            q)
                is_mode_quiet=1

                ;;
            x)
                el_array_member_add "$OPTARG" "${targets_cc[@]}" ; targets_cc=("${_out[@]}")
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "CC: $OPTARG"
                fi

                ;;
            X)
                el_array_member_add "$OPTARG" "${targets_bcc[@]}" ; targets_bcc=("${_out[@]}")
                if ! ((is_mode_quiet)) ; then
                    el_explain 2 "BCC: $OPTARG"
                fi

                ;;
            \?)
                el_error "Invalid option: -$OPTARG"
                usage
                exit 1
                ;;
            :)
                el_error "Option -$OPTARG requires an argument."
                usage
                exit 1
                ;;
        esac
    done

    # is our message from stdin ? use it
    if ((is_stdin)) ; then
        #message="$( cat 2>&1 | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" )"
        #cat 2>&1 > "$tempfile_tmp"
        #message="$tempfile_tmp"
        message="$(</dev/stdin)"

        # check and unset
        if [[ -n "$message" ]] ; then
            echo "$message" > "$tempfile_tmp"
        else
            unset is_stdin
        fi
    fi


    do_email_send

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
