#! /bin/sh -e

PROGRAM=lr_log2mail

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

. $etcdir/profile_lean
. $etcdir/defaults

test -z "$LR_ID" && LR_ID=`lr_tag`
export LR_ID
tag="all all $LR_ID $PROGRAM"

echo >&2 "$tag info started with $*"

USAGE="Usage $PROGRAM [-c <report_cfg>] [-i] [-o <outputformat>] [-s subject] service sendto+"

# get options (x)
output_flag=""
image_flag=""
cfg_flag=""
subject=""
while getopts :o:s:c:ivah\? o; do
    case $o in
	a)
	    echo >&2 "$tag warning detected obsolete -a option. Use -o xml instead"
	    output_flag="-o xml"
	    ;;
	c)  cfg_flag="-c $OPTARG"
	    ;;
        o)  output_flag="-o $OPTARG"
            ;;
	i)  image_flag="-i"
	    ;;
        s)  subject="$OPTARG"
            ;;
        h | "?")
            echo >&2 "$tag notice $USAGE"
            exit 0
            ;;
        v)
            echo >&2 "$tag notice $PROGRAM" '$Id: lr_log2mail.in,v 1.46 2002/08/19 14:34:34 vanbaal Exp $,' "shipped with Lire 1.1"
            exit 0
            ;;
        *)
            echo >&2 "$tag err $USAGE"
            exit 1
            ;;
    esac
done

# yes, the '|| true' is needed. solaris' /bin/sh feels it should bawl out when
# encountering an 'expr 1 - 1', while running -e
shift `expr $OPTIND - 1 || true`

if test $# -lt 2
then
    echo >&2 "$tag err $USAGE"
    exit 1
fi

if test $# -gt 2
then
    echo >&2 "$tar warning found extra arguments."
    echo >&2 "$tar warning interpreted as pre-Lire 1.1 usage."
    echo >&2 "$tar warning please fix your wrapper scripts, and call this script as $USAGE"
    shift
fi

LR_SERVICE=`lr_check_service "$1"`
if test -z "$LR_SERVICE"
then
    echo >&2 "$tag err lr_check_service failed"
    exit 1
fi
shift

# e.g. joe,ann@foo.bar
echo >&2 "$tag info will send to $*"

tag="all $LR_SERVICE $LR_ID $PROGRAM"

if /usr/bin/perl -MMIME::Tools -e 'exit 0' 2>/dev/null
then
    :
else
    cat >&2 <<EOF
$tag err can't send email: the needed MIME::Entity perl module isn't available
$tag err Please install the MIME::Tools perl modules from a local CPAN mirror.
$tag err Consult the Lire User's Manual for more informations.
EOF
    #' Fontification hack
    exit 1
fi

if test -n "$subject"
then
    if test -z "$LR_EXTID"
    then
        LR_EXTID=`echo $subject | sed 's/ /_/g'`
        newextid=yes
    fi
fi

subject="[LogReport] $LR_SERVICE report (was: $subject)"
errsubject="[LogReport] Error in $LR_SERVICE report (was: $subject)"
test -z "$LR_EXTID" && LR_EXTID=UNSET && newextid=yes
export LR_EXTID

if test -n "$LR_ARCHIVE"
then
    if test -n "$newextid"
    then
        if lr_db_store $LR_ID extid "$LR_EXTID"
        then
            :
        else
            echo >&2 "$tag crit cannot lr_db_store $LR_ID extid $LR_EXTID, exiting"
            exit 1
        fi
    fi
fi


if test ! -f "$LR_SIGNATUREFILE"
then
    echo >&2 "$tag err no signaturefile $LR_SIGNATUREFILE, exiting"
    exit 1
fi

if test ! -f "$LR_DISCLAIMERFILE"
then
    echo >&2 "$tag err no disclaimerfile $LR_DISCLAIMERFILE, exiting"
    exit 1
fi

if test ! -d "$TMPDIR"
then
    echo >&2 "$tag notice dir $TMPDIR does not exist, creating it"
    if mkdir $TMPDIR
    then
        :
    else
        echo >&2 "$tag err cannot create $TMPDIR, exiting"
        exit 1
    fi
fi

ERRFILE=$TMPDIR/$PROGRAM.$LR_SERVICE.$LR_ID.errors
if touch $ERRFILE 2>/dev/null
then
    # creation of errorfile indicates an error. we shouldn't create it now.
    rm $ERRFILE
else
    echo >&2 "$tag err cannot touch errorfile $ERRFILE, exiting"
    exit 1
fi

# Test output format requirements
if lr_xml2report -t $image_flag $output_flag /dev/null
then
    :
else
    echo >&2 "$tag err missing requirements for the selected output format"
    { cat <<EOT
Could not generate a report from your log file. Some required tools necessary 
for the selected output format are missing.
EOT
} > $ERRFILE
    lr_mail -s "$errsubject" text/plain $ERRFILE "$@" || echo >&2 "$tag err lr_mail failed"
    exit 1
fi

LOGFILE=$TMPDIR/$PROGRAM.$LR_SERVICE.$LR_ID.log
if lr_inflate > $LOGFILE
then
    :
else
    echo >&2 "$tag err lr_inflate failed"
    { cat <<EOT
Could not generate a report from your log file. We failed to decompress
your log file.
EOT
} > $ERRFILE
    lr_mail -s "$errsubject" text/plain $ERRFILE "$@" || echo >&2 "$tag err lr_mail failed"
    exit 1
fi

echo >&2 "$tag info gonna run lr_log2xml $cfg_flag $LR_SERVICE"
XMLREPORTFILE=$TMPDIR/$PROGRAM.$LR_SERVICE.$LR_ID.report.xml

if lr_log2xml $cfg_flag $LR_SERVICE < $LOGFILE > $XMLREPORTFILE
then
    :
else
    echo >&2 "$tag err lr_log2xml $cfg_flag $LR_SERVICE failed"
    echo >&2 "$tag notice keeping $LOGFILE for debug"
    echo >&2 "$tag notice you might like to inspect and clean up the Lire database in $LR_DBFILE"
    rm -f $XMLREPORTFILE
    { 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 "$@" || echo >&2 "$tag err lr_mail failed"
    exit 1
fi

eval `lr_check_errlines`
if test -n "$lr_check_errlines_OK"
then
    :
else
    echo >&2 "$tag warning probably bogus log: $lr_check_errlines_LOGLINES lines in log, while found $lr_check_errlines_ERRORLINES lines with errors"
    { cat <<EOT
WARNING: Logfile may be bogus. $lr_check_errlines_ERRORLINES lines on the $lr_check_errlines_LOGLINES lines in the
log had errors.

This may be because you sent a log file that doesn't strictly contain
$LR_SERVICE logs. This is probable if you sent a syslog log file without
filtering it to keep only the logs relevant to the $LR_SERVICE service.

It could also be because you sent a log file in the wrong format or
a file that isn't a $LR_SERVICE log file.

A report was generated for the $lr_check_errlines_DLFLINES records that could be extracted
from your log file.

EOT
} > $ERRFILE
fi

if lr_xml2mail -s "$subject" $image_flag $output_flag -x $XMLREPORTFILE "$@"
then
    :
else
    { cat <<EOF

An error occured while formatting your report. 
EOF
} >> $ERRFILE
fi

echo >&2 "$tag info running lr_archive_log -l $LOGFILE -x $XMLREPORTFILE"
if lr_archive_log -l $LOGFILE -x $XMLREPORTFILE
then
    echo >&2 "$tag info lr_archive_log succeeded"
else
    echo >&2 "$tag info lr_archive_log failed"
fi

if test -f $ERRFILE
then
    lr_mail -s "$errsubject" text/plain $ERRFILE "$@" || echo >&2 "$tag err lr_mail failed"
    if test -n "$LR_KEEP"
    then
	echo >&2 "$tag info keeping $ERRFILE on your request. Remove manually."
    else
	rm $ERRFILE
    fi
fi

echo >&2 "$tag info stopped"

exit 0

POD=<<'EOPOD'

=pod

=head1 NAME

B<lr_log2mail> - send a report generated from a log file by email

=head1 SYNOPSIS

B<lr_log2mail> B<[I<options>]> I<service> I<addresses>...

B<lr_log2mail> B<-h>

B<lr_log2mail> B<-v>

=head1 OPTIONS

=over 4

=item B<-h>

Prints usage information and exits.

=item B<-c> I<report_cfg>

Use the file I<report_cfg> as the report configuration file instead of
the default one.

=item B<-i>

Generate charts for all reports that support it. Normally, charts will
be generated only if the variable I<LR_INCLUDEIMAGES> is set to 1.

=item B<-o> I<output format>

One of B<pdf>, B<html>, B<html_page>, B<xhtml>, B<xhtml_page>, B<txt>,
B<docbookx>, B<rtf>, B<logml> and B<xml>. Per default, simple txt output is
generated. For the www and email superservice also the B<logml> output format
is available.  The B<html> and B<xhtml> output format behave exactly the same
as B<html_page> and B<xhtml_page>, respectively: they generate the complete
report on one page, since this is nicer in email messages.  The B<html> and
B<xhtml> options are just supplied for compatibity with lr_log2report(1) and
friends.  (Refer to the Lire User Manual for a description of this format.)

=item B<-s> I<subject>

A keyword that will be included in the subject of the outgoing mail
message. Used by the Online Responder to match outgoing email to
incoming mail, but it can also be useful for other purpose. The email
subject will look like:

[LogReport] I<LR_SERVICE> report (was: I<subject>)

=item B<-v> 

Prints Lire's version and exits.

=back

=head1 DESCRIPTION

The B<lr_log2mail> command is similar to the lr_log2report(1) command with the
difference that the report is sent by email instead of being output on STDOUT.
The log file is read from STDIN. The log file's format is specified using the
I<service> argument.  (Run

  lr_run lr_check_service -l

for a list of supported services.) All remaining arguments are interpreted as
email addresses to which to send the report.

The report will be encapsulated in a MIME email appropriate for the
output format. For example, ASCII reports will be sent inline, PDF
reports will be sent as a file attachment and HTML reports should
appear inline in a HTML-capable mail reader.

The I<LR_SIGNATUREFILE> and I<LR_DISCLAIMERFILE> files 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
I<LR_EXPLANATIONFILE> file will be included in the outgoing message.

The From and Reply-To headers in the outgoing emails are set to the
values of the I<LR_FROM> and I<LR_REPLYTO> environment variables.

The environment variable I<LR_ID> is used in tags in debug messages, which get
printed to stdout.  In case I<LR_ID> is not set, lr_log2mail(1) itself
generates one.

When run from the commandline, it's useful to run it under lr_run(1), to
be able to tune the amount of debug output generated.

=head1 EXAMPLE

 % lr_run lr_log2mail -s "bind8 report" bind8_query \
     root "Joe User <joe@example.com>" < /var/log/query.log

=head1 SEE ALSO

lr_log2report(1), lr_anonymize(1), lr_xml2report(1), lr_xml2mail(1), 
lr_rawmail2mail(1), documentation in the Lire User Manual

=head1 VERSION

$Id: lr_log2mail.in,v 1.46 2002/08/19 14:34:34 vanbaal Exp $

=head1 COPYRIGHT

Copyright (C) 2000, 2001, 2002 Stichting LogReport Foundation
LogReport@LogReport.org

This program 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 or write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.

=head1 AUTHORS

Joost van Baal <joostvb@logreport.org>

Francis J. Lacoste <flacoste@logreport.org>

=cut

EOPOD



