#!/bin/sh
#------------------------------------------------------------------------------
# /opt/files/usr/local/bin/msmtp.sh                                      v0.9.9
#
# Creation:     2003-05-02  t_klingl
# Last Update:  2011-07-24  Christoph Fritsch <fli4l@dechristo.net>
#------------------------------------------------------------------------------

#---------------------------------------
# Hilfsfunktionen
#---------------------------------------
#---------------------------------------
# usage ()
#---------------------------------------
usage ()
{
    echo "usage: msmtp.sh -m MIME_Mailfile"
    echo "       msmtp.sh -f from"
    echo "                -t to" 
    echo "               [-cc \"comma_separated_cc_address_list\"]"
    echo "               [-bcc \"comma_separated_bcc_address_list\"]"
    echo "                -r \"reply-to\""
    echo "                -s \"subject\""
    echo "                -b \"mailbody_text\" | \"/absolute/path/to/body.txt\""
    echo "               [-d directory [-rp regex_positiv] [-rn regex_negativ]]"
    echo "               [[MIME-Type:]attachment] ..."    
    echo "               [-c charset]"
    echo "               - read mail from STDIN (see documentation)"
}

#---------------------------------------
# getArg (string, string)
#---------------------------------------
getArg ()
{
    ARG1=$1
    ARG2=$2
    
    if [ "${ARG2}" != "" ];
    then
        case "${ARG1}"
        in
            -m)  FILE="${ARG2}";;
            -f)  FROM="${ARG2}";;
            -r)  REPLYTO="${ARG2}";;
            -t)  TO="${ARG2}";;
            -s)  SUBJECT="${ARG2}";;
            -b)  BODY="${ARG2}";;
            -cc) CC="${ARG2}";;
            -bcc) BCC="${ARG2}";;
            -d)  DIR="${ARG2}";;
            -rp) REGEXPOS="${ARG2}";;
            -rn) REGEXNEG="${ARG2}";;            
            -c)  CHARSET="${ARG2}";;
             *) break 2;;
        esac
        return 0
    fi
    return 1    
}

#---------------------------------------
# log (string)
#---------------------------------------
log ()
{
    TEXT=$1

    if [ "${MSMTP_LOGFILE}" != "" ]; then
        case "${MSMTP_LOGFILE}"
        in
            syslog) logger "msmtp: ${TEXT}";;
            *)      echo "${DATE} msmtp: ${TEXT}" >> ${MSMTP_LOGFILE};;
        esac
    fi
    
    return 1
}

#---------------------------------------
# insertHeader (string, string)
#---------------------------------------
insertHeader ()
{
    KEY="${1}"    
    VALUE="${2},"
    COUNTER=1        
    
    # Schluessel ausgeben    
    echo -n "${KEY}: "        
    
    while [ 1 ]    
    do        
        TMP="`echo \"${VALUE}\" | cut -d\",\" -f ${COUNTER} -n`"
        if [ "${TMP}" != "" ]; then            
            if [ ${COUNTER} -gt 1 ]; then
                echo -n ","
            fi
            echo -n "${TMP}"
            COUNTER=`expr ${COUNTER} + 1`
        else            
            break 2;
        fi    
    done
    echo ""
}


#---------------------------------------
# attach (string)
#---------------------------------------
attach ()
{
    FILES=$1
    
    HELP1=`echo "${FILES}" | sed 's/^\(.*\):\(.*\)/\1/g'`
    HELP2=`echo "${FILES}" | sed 's/^\(.*\):\(.*\)/\2/g'`

    #echo "Help1=${HELP1}"
    #echo "Help2=${HELP2}"
    if [ "${HELP1}" = "${HELP2}" ]; then
        # kein ContentType angegeben
        # falls vorhanden, 'file' zur Bestimmung nutzen
        if [ "${FILECMD}" = "1" ]; then
            CONTENTTYPE=`/usr/bin/file -i "${FILES}" | cut -d":" -f 2-`
        else
            CONTENTTYPE=${DEFAULTCT}
        fi
    else
        # angegebener ContentType hat Vorrang
        CONTENTTYPE="${HELP1}"
        FILES="${HELP2}"
    fi
    
    BASENAME=`basename "${FILES}"`
    {
        echo -e "${BOUNDARY}"
        echo -e "Content-Type:${CONTENTTYPE}; name=\"${BASENAME}\""
        echo -e "Content-Disposition: attachment"
        echo -e "Content-Transfer-Encoding: base64"
        echo -e ""
    } >> ${SPOOLFILE}
    
    mmencode "${FILES}" >> ${SPOOLFILE}
    
    {
        echo -e ""
    } >> ${SPOOLFILE}
    
    return 1
}

#---------------------------------------
# Variablen initialisieren
#---------------------------------------
TO=''
FROM=''
REPLYTO=''
FILE=''
SUBJECT=''
BODY=''
CC=''
BCC=''
DIR=''
REGEXPOS=''
REGEXNEG=''
CHARSET=''

#---------------------------------------
# Parameter bestimmen und einlesen
#---------------------------------------
while test $# -gt 0
do
    getArg "$1" "$2"
    if [ "$?" = "1" ];
    then
        break;
    fi
    shift
    shift
done

#---------------------------------------
# alle Pflicht-Parameter vorhanden ?
#---------------------------------------
if [ "${FILE}" != "" ];
then
    if [ "${FROM}" != "" -o "${TO}" != "" -o "${SUBJECT}" != "" -o "${BODY}" != "" ];
    then
        usage
        exit 1
    fi
else
    if [ "${FROM}" = "" -o "${TO}" = "" -o "${SUBJECT}" = "" -o "${BODY}" = "" ];
    then
        usage
        exit 1
    fi
fi
#---------------------------------------
# Variablen der Config-Datei inkludieren
#---------------------------------------

. /etc/msmtp/msmtp_skripte.conf

#---------------------------------------
# Defaultwerte oder benutzerdefinierte Werte ?
#---------------------------------------
if [ "${CHARSET}" != "" ]; then    
    MSMTP_CHARSET="${CHARSET}"
fi

#---------------------------------------
# Hilfsvariablen
#---------------------------------------

TIMESTAMP=`date +%Y%m%d%H%M%S`      # als eineindeutigen Dateinamen verwenden
DATE=`date '+%a, %d %b %Y %H:%M:%S %z'` 
                                    # fuer das Datumsfeld der EMail
SPOOLFILE="${MSMTP_SPOOL_DIR}/${TIMESTAMP}.mail"
                                    # eindeutiger Name des Spoolfiles
SPOOLFILE_SHORT="${MSMTP_SPOOL_DIR}/${TIMESTAMP}"
                                    # eindeutiger Kurzname des Spoolfiles
BOUNDARY="--========Boundary155661039885988"
                                    # Abschnittbegrenzer
DEFAULTCT="application/octet-stream"
                                    # falls kein MIME-Type angegeben und 'file' nicht vorhanden ist
DEFAULTREGEXPOS="^.*$"
                                    # regulaerer Ausdruck (positiv), matcht auf alle Dateinamen
DEFAULTREGEXNEG="^$"
                                    # regulaerer Ausdruck (negativ), matcht auf keinen Dateinamen

REGEXPOSFILE="${MSMTP_SPOOL_DIR}/${TIMESTAMP}.regexpos"
REGEXNEGFILE="${MSMTP_SPOOL_DIR}/${TIMESTAMP}.regexno"
                                    
#---------------------------------------
# sind 'file', "egrep" und "uuidgen"-Hilfprogramme vorhanden ?
# wir gehen davon aus, wenn OPT_MSMTPPRO gesetzt ist
#---------------------------------------

if [ "`echo ${MSMTP_PRO} | grep -i '^yes$'`" = "" ];
then
    FILECMD="0"
    GREPCMD="grep"
    EGREP="0"
    GUID=${TIMESTAMP}
else
    FILECMD="1"
    GREPCMD="egrep -E -f"
    EGREP="1"
    GUID=`uuidgen`
fi

#---------------------------------------
# Variablen einlesen & belegen
#---------------------------------------

if [ "${FILE}" = "" ]; then
    #---------------------------------------
    # zweite Aufrufvariante
    #---------------------------------------
    
    if [ "$1" != "" ]; then
        ATTACHMENTS=1
    else
        ATTACHMENTS=0
    fi
    
    if [ "${REGEXPOS}" = "" ]; then
        REGEXPOS="${DEFAULTREGEXPOS}"
    fi
    echo "${REGEXPOS}" | cat > ${REGEXPOSFILE}
    
    if [ "${REGEXNEG}" = "" ]; then
        REGEXNEG="${DEFAULTREGEXNEG}"
    fi
    echo "${REGEXNEG}" | cat > ${REGEXNEGFILE}
    
    #Mailfile erstellen
    {
        # FROM        
        insertHeader "From" "${FROM}"
        
        # TO
        insertHeader "To" "${TO}"
        
        # DATE
        echo -e "Date: ${DATE}"
        
        # Subject-Kodierung herstellen
        SUBJECT_TMP=`echo "${SUBJECT}" | mmencode -q`
        if [ "${SUBJECT_TMP}" = "${SUBJECT}" ];    then
            echo -e "Subject: ${SUBJECT}"
        else
            echo -e "Subject: =?${MSMTP_CHARSET}?Q?${SUBJECT_TMP}?="
        fi
        
        # SENDER
        echo -e "X-Sender: opt_msmtp"
        
        # MESSAGE-ID
        echo -e "Message-ID: <${GUID}@${MSMTP_HOSTNAME}>"
    } > ${SPOOLFILE}
    
    if [ "${REPLYTO}" != "" ]; then
    {
        # REPLY-TO
        insertHeader "Reply-To" "${REPLYTO}"
    } >> ${SPOOLFILE}
    fi
    
    # CC
    if [ "${CC}" != "" ]; then
    {
        insertHeader "Cc" "${CC}"
    } >> ${SPOOLFILE}
    fi
    
    # BCC
    if [ "${BCC}" != "" ]; then
    {
        insertHeader "Bcc" "${BCC}"
    } >> ${SPOOLFILE}
    fi    
    
    {
        echo -e "MIME-Version: 1.0"
        echo -e "Content-Type: multipart/mixed; boundary=\"`echo ${BOUNDARY} | sed 's/^..\(.*\)$/\1/g'`\""
        echo -e ""
        echo -e "This is a MIME encapsulated multipart message -"
        echo -e "please use a MIME-compliant e-mail program to open it."
        echo -e ""
        echo -e "${BOUNDARY}"
        echo -e "Content-Type: text/plain; charset=\"${MSMTP_CHARSET}\""
        echo -e "Content-Transfer-Encoding: quoted-printable"
        echo -e ""
    } >> ${SPOOLFILE}
    
    if [ "`echo ${BODY} | cut -c 1`" = "/" ];
    then
        # Datei inkludieren
        cat "${BODY}" | mmencode -q >> ${SPOOLFILE}
    else
        echo "${BODY}" | mmencode -q >> ${SPOOLFILE}
    fi
    
    {
        echo -e ""
    } >> ${SPOOLFILE}
    
    if [ "$ATTACHMENTS" = "1" ]; then
        
        for FILES
        do
            attach "${FILES}"
        done
    
    fi
    
    if [ "${DIR}" != "" ]; then

            AKTDIR=`pwd`
            cd ${DIR}
        for FILES in `ls "${DIR}"`
        do
            if [ "${EGREP}" = "1" ]; then
                FILES=`echo "${FILES}" | ${GREPCMD} ${REGEXPOSFILE}`
            else
                 FILES=`echo "${FILES}" | ${GREPCMD} ${REGEXPOS}`
            fi
            if [ "${FILES}" != "" ]; then
                if [ "${EGREP}" = "1" ]; then
                    RESULT=`echo "${FILES}" | ${GREPCMD} ${REGEXNEGFILE}`
                else
                    RESULT=`echo "${FILES}" | ${GREPCMD} ${REGEXNEG}`
                fi
                if [ "${RESULT}" != "" ]; then
                    FILES=""
                fi
            fi
            if [ "${FILES}" != "" ]; then
                #echo "wird angehaengt : ${FILES}"
                attach "${DIR}/${FILES}"
            fi
        done
        cd ${AKTDIR}    
    fi
    
    {
        echo -e "${BOUNDARY}--"
        echo -e ""
    } >> ${SPOOLFILE}

    rm ${REGEXPOSFILE}
    rm ${REGEXNEGFILE}
    chmod 666 ${SPOOLFILE}
    #---------------------------------------
    # Ende zweite Aufrufvariante
    #---------------------------------------

else

    #---------------------------------------
    # erste Aufrufvariante
    #---------------------------------------
    if [ "${FILE}" = "" ]; then
        usage
        exit 1;
    fi

	case "${FILE}" in
		"-")
			# stdinput lesen
			cat > ${SPOOLFILE}
		;;
		*)	# ins SPOOL-Verzeichnis kopieren
		    cp ${FILE} ${SPOOLFILE}
		;;
	esac

    chmod 666 ${SPOOLFILE}

    #---------------------------------------
    # Ende erste Aufrufvariante
    #---------------------------------------
fi    

#---------------------------------------
# Sofort versenden ?
#---------------------------------------

if [ "${MSMTP_SEND_AT_ONCE}" = "yes" ];
then
    /usr/local/bin/msmtp_send.sh "${SPOOLFILE}"
    if [ -e "${SPOOLFILE}" ];
        then
        mv ${SPOOLFILE} ${SPOOLFILE_SHORT}.retry1
    fi
else
    # erst spaeter versenden
    mv "${SPOOLFILE}" "${SPOOLFILE}.retry0"
fi

exit 0