#! /bin/sh -e

PROGRAM=lr_spool

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

lire_log "info $PROGRAM started with $@"

if test $# -lt 1
then
    lire_log "err please give at least 2 args"
    exit 1
fi

SPOOLDIR="$1"; shift
COMMAND="$@"

if test ! -d $SPOOLDIR
then
    lire_log "err Directory $SPOOLDIR doesn't exist"
    exit 1
fi

ls $SPOOLDIR/* 2>/dev/null | while read f
do
    mv $f $TMPDIR

    file=`basename $f`
    file="$TMPDIR/$file"

    LR_ID=`lr_tag`
    export LR_ID

    lire_log "info gonna run $COMMAND < $file"
    lire_log "info gonna rm $file or mv it to $LR_FAILEDDIR"

    if $COMMAND < $file
    then
        # $COMMAND is supposed to save stdin in the archive, if desired.
        rm $file
    else
        lire_log "err $COMMAND on file '$file' failed, moving to $LR_FAILEDDIR"
        mv $file $LR_FAILEDDIR
    fi
done

lire_log "info $PROGRAM stopped"

exit 0

POD=<<'EOPOD'

=pod

=head1 NAME

lr_spool - feed files in a spooldir to a command

=head1 SYNOPSIS

B<lr_spool> I<spooldir> I<command>

=head1 DESCRIPTION

For each file I<f> in directory I<spooldir>, B<lr_spool> generates a unique
LR_ID, exports it as a shell variable, and runs

 command < f

. Before executing I<command>, I<f> is moved to $TMPDIR. If I<command> exits
successfully, I<f> is removed (I<command> is assumed to save stdin to a file,
if it feels this is appropriate), else I<f> is moved to I<LR_FAILEDDIR>.

In case any of I<spooldir>, I<TMPDIR> or I<LR_FAILEDDIR> doesn't exist, it's
created on the fly.

This script is invoked by lr_spoold(1), which uses lr_processmail(1) as
the I<command>.

=head1 BUGS

The directory I<spooldir> is created using plain mkdir -p.  If I<spooldir> is
supposed to be part of a Maildir structure, only .../new/ is created.  This
does not satisfy for a valid Maildir.  One has to verify manually wether
I<spooldir> is part of a valid Maildir, and create it manually, on such a
system.

=head1 SEE ALSO

lr_spoold(1), the Lire User Manual, especially the Overview section.

=head1 VERSION

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

=head1 AUTHOR

Joost van Baal <joostvb@logreport.org>

=head1 COPYRIGHT

Copyright (C) 2000-2003 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.
=cut

EOPOD

