#! /bin/sh -e

PROGRAM=lr_processmail

# dereference sysconfdir's prefix dependency
prefix="/usr/local"
etcdir="${prefix}/etc/lire"
. $etcdir/defaults

if test -z "$LR_ID"
then
    LR_ID=`lr_tag || echo UNSET`
fi

if test $# -eq 0
then
    lire_log "err please give 1 arg, indicating service"
    exit 1
fi

lire_log "info started with $@"

LR_SERVICE=$1; shift

newfile=`lr_tempfile $PROGRAM.$LR_SERVICE.$LR_ID.XXXXXX.mail`
lr_mark_for_cleanup $newfile

if test -z "$gzip_path"
then
    lire_log "err gzip(1) isn't available"
    exit 1
fi

if /usr/bin/perl -MMIME::Tools -e 'exit 0' 2>/dev/null
then
    :
else
    lire_log "err can't parse email: the needed MIME::Entity perl module isn't available"
    lire_log "err Please install the MIME::Tools perl modules from a local CPAN mirror."
    lire_log "err Consult the Lire User's Manual for more informations."
    exit 1
fi

extrafile=`lr_tempfile $PROGRAM.$LR_SERVICE.$LR_ID.XXXXXX.mail`
lr_mark_for_cleanup $extrafile

if test -z "$lr_mail_signature"
then
    lire_log "err Missing lr_mail_signature setting."
    exit 1
fi
cat $lr_mail_signature >> $extrafile

if test -z "$lr_mail_disclaimer"
then
    lire_log "err Missing lr_mail_disclaimer setting."
    exit 1
fi
cat $lr_mail_disclaimer >> $extrafile

if test -z "$lr_mail_explanation"
then
    lire_log "err Missing lr_mail_explanation setting."
    exit 1
fi

errfile=`lr_tempfile $PROGRAM.$LR_SERVICE.$LR_ID.XXXXXX.errors`
lr_mark_for_cleanup $errfile

cat >> $newfile

lire_log "info processing $newfile"
lire_log "info running lr_getbody"

# this sets lr_getbody_BODYFILE, lr_getbody_SUBJECTFILE 
# and lr_getbody_SUBMITTER
eval `lr_getbody $newfile || true`

# we use lr_getbody_SUBMITTER _unquoted_.  This variable is constructed
# using MIME::Tools, so is reasonably trusted.  We should allow for
# embedded spaces, separating multiple addresses to sent the report to.
if test -z "$lr_getbody_OK"
then
    lire_log "warning lr_getbody didn't completed successfully"
    if test -n "$lr_getbody_SUBMITTER"
    then
	lire_log "err sending error message to $lr_getbody_SUBMITTER"
	{ cat <<EOF
FATAL ERROR: We failed to parse your message.

There was an encoding problem with your message. Make sure that you
send your log file using a MIME compliant mail reader.

Contact the administrator of this responder for more help.

EOF
	} >> $errfile
	lr_mail -s "[LogReport] Error in $LR_SERVICE report (was: $lr_getbody_SUBJECT)" text/plain $errfile $lr_getbody_SUBMITTER || echo >&2 "lr_mail failed"
	exit 1
    else
	lire_log "err No submitter can be found. Keeping $newfile for debugging"
	exit 1
    fi
else
    lire_log "info lr_getbody gave FILE '$lr_getbody_FILE'"
    lire_log "info lr_getbody gave SUBJECT '$lr_getbody_SUBJECT'"
    lire_log "info lr_getbody gave SUBMITTER '$lr_getbody_SUBMITTER'"
fi

bodyfile="$lr_getbody_FILE"
if test -z "$bodyfile"
then
    # Empty body
    bodyfile="`lr_tempfile $PROGRAM.$LR_ID.XXXXXX.body`"
fi
lr_mark_for_cleanup $bodyfile
submitter="$lr_getbody_SUBMITTER"

output_flag=
if echo "$lr_getbody_SUBJECT" | grep "^anon" >/dev/null
then
    output_flag='-o xml'
    lr_getbody_SUBJECT=`echo "$lr_getbody_SUBJECT" | cut -d ' ' -f2-`
    cat $lr_mail_explanation >> $extrafile
fi

subject="[LogReport] $LR_SERVICE report (was: $lr_getbody_SUBJECT)"
errsubject="[LogReport] Error in $LR_SERVICE report (was: $lr_getbody_SUBJECT)"

# Sets LR_EXTID to an encoded form of the sender address
# Only keep alphanumeric characters, dot, hyphen, dash, plus and at
# Lowercase the email
LR_EXTID=`echo "$submitter" | /usr/bin/perl -pe 'tr/a-zA-Z0-9\@._-//cd; tr/A-Z/a-z/; s/^\.+//;'`
export LR_EXTID


if lr_log2mail -q $output_flag  --log-file $bodyfile --subject "$subject" --extra-file $extrafile $LR_SERVICE $submitter
then
    :
else
    lire_log "err lr_log2mail $output_flag  --log-file $bodyfile --subject "$subject" --extra-file $extrafile $LR_SERVICE $submitter failed"
    { cat <<EOT
FATAL ERROR: We failed to generate a report from your log file.

This is probably because your log file isn't a $LR_SERVICE log file.
Please verify that your submitted log file is a valid $LR_SERVICE log
file.

This error could also be caused by an encoding problem caused by your
mailer. Some mailers are known to wrap long lines by inserting newline
characters. This breaks our log parser. Compressing the log file using
zip or gzip and sending it as a regular MIME attachment can help
prevent this behavior.

Contact the administrator of this responder for more help.

EOT
    #' Quoting bug
} >> $errfile
    lr_mail -s "$errsubject" text/plain $errfile $submitter || lire_log "err lr_mail failed"
    exit 1
fi

if test -n "$lr_archive"
then
    # go store $newfile in the archive

    # due to the way the archive is set up, we need to know this services'
    # superservice.  hrm...

    # we assume service is valid, since we're being called via an online
    # responder: these (should) have current mailbox names only
    LR_SUPERSERVICE=`lr_check_superservice $LR_SERVICE`

    ARCHIVEDIR=$lr_archive_dir/email/raw/$LR_SUPERSERVICE/$LR_SERVICE/$LR_EXTID
    ARCHIVEFILE=$ARCHIVEDIR/$LR_ID.msg.gz

    lire_log "notice storing compressed $newfile in $ARCHIVEFILE"
    test -d $ARCHIVEDIR || mkdir -p $ARCHIVEDIR
    $gzip_path --best -c $newfile > $ARCHIVEFILE
fi

lire_log "info stopped"

exit 0

POD=<<'EOPOD'


=pod

=head1 NAME

B<lr_processmail> - read an email message and invoke lr_log2mail(1)

=head1 SYNOPSIS

B<lr_processmail> I<service>

=head1 DESCRIPTION

B<lr_processmail> reads an email message from STDIN, parses the message
using lr_getbody(1) and invokes lr_log2mail(1) to process the extracted 
log file.

The environment variable LR_ID is used as an identifier, which shows up
in debug messages, and in names of temporary files, so that Lire jobs
can get tracked.  A Lire job currently is identified with one email
message or log file.

This script is invoked by lr_spool(1).

The files specified in the I<lr_mail_signature> and
I<lr_mail_disclaimer> configurartion variables are sent along the
generated report.

If an error occurs in the report generation process, an email message
explaining possible sources for the error will be sent to the email
addresses.

The B<-o xml> format is useful in the case the log file was anonymized
so that it can be deanonymized before being formatted using
lr_xml2report(1) or lr_xml2mail(1). When using that format, the file
specified in the I<lr_mail_explanation> configuration variable will be
included in the outgoing message.

=head1 EXAMPLE

 $ lr_processmail combined < /var/spool/lire/done/985327208.21242.mailhost

=head1 SEE ALSO

lr_spool(1), documentation in the Lire User Manual

=head1 VERSION

$Id: lr_processmail.in,v 1.16 2006/07/23 13:16:33 vanbaal Exp $

=head1 AUTHOR

Joost van Baal <joostvb@logreport.org>, based on an idea by Edwin Groothuis

=head1 COPYRIGHT

Copyright (C) 2000-2003 Stichting LogReport Foundation LogReport@LogReport.org

This file is part of Lire.

Lire is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program (see COPYING); if not, check with
http://www.gnu.org/copyleft/gpl.html.

=cut

EOPOD


