#!/bin/sh
#------------------------------------------------------------------------------
# /opt/files/usr/local/bin/msmtp_send.sh                                  v0.1m
#
# Versendet das uebergebene File, prueft den Versandstatus und informiert
# darueber das aufrufende Programm
#
# Exitcodes : 0 = ok
#             1 = Fehler bei Authentifizierung
#             2 = Fehler beim Versenden
#             3 = unbekannter Fehler (Fehler beim Versenden oder Authentifizierung)
#
# Creation:     2003-05-04  t_klingl
# Last Update:  2006-03-27  dke
#------------------------------------------------------------------------------

#---------------------------------------
# Variablen belegen & inkludieren
#---------------------------------------
. /etc/msmtp/msmtp_skripte.conf
FILE=$1
MSMTPCOMMAND="/usr/local/bin/msmtp -C /etc/msmtp/msmtp.conf"
DATE=`date`

#---------------------------------------
# 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
}

#---------------------------------------
# POP3-before-smtp ???
#---------------------------------------
if [ "${MSMTP_SMTP_AUTH}" = "pop" ]; then
    echo -e "user ${MSMTP_POP3_USERNAME}\r\npass ${MSMTP_POP3_PASSWORD}\r\nquit\r" | netcat -i 1 ${MSMTP_POP3_SERVER} ${MSMTP_POP3_PORT} | grep -q ^ERR
        
    if [ "$?" = "0" ]; then
       log "error on pop-before-smtp, check server, port and authentication data"
    fi
fi

# Send Message

${MSMTPCOMMAND} -t < ${FILE}

if [ $? != "0" ]; then
    # Fehler beim Versenden
    ERRCODE=$?
    TRY=`echo "${FILE}" | sed 's/^\(.*\.retry\)\(.*\)$/\2/g' | sed 's/[^0-9]//g'`
    log "error sending mail ${FILE} (${ERRCODE}), attempt ${TRY}"
else
    # alles ok, file kann geloescht werden
    log "mail ${FILE} sent successfully"
    rm "${FILE}"
fi
