#! /bin/sh -e

# $Id: lr_spool.in,v 1.6 2001/09/01 20:23:05 flacoste Exp $

#
# Copyright (C) 2000-2001 Stichting LogReport Foundation LogReport@LogReport.org
# 
#     This program 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.
#

PROGRAM=lr_spool

# superservice service logidentifier
tag="all all none $PROGRAM"

echo >&2 "$tag info $PROGRAM started with $@"

if test $# -lt 1
then
    echo >&2 "$tag err please give at least 2 args"
    exit 1
fi

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

test -z "$TMPDIR" && \
    echo >&2 "$tag err TMPDIR not set. is it in defaults?"
test -z "$FAILEDDIR" && \
    echo >&2 "$tag err FAILEDDIR not set. is it in defaults?"

for d in $SPOOLDIR $TMPDIR $FAILEDDIR
do
    if test ! -d $d
    then
        mkdir -p $d
    fi
done

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

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

    # since we were started by lr_spoold, we can find lr_tag in our PATH
    LR_ID=`lr_tag`
    export LR_ID

    idtag="all all $LR_ID $PROGRAM"

    echo >&2 "$idtag info gonna run $COMMAND < $file"
    echo >&2 "$idtag info gonna rm $file or mv it to $FAILEDDIR"

    if $COMMAND < $file
    then
        # $COMMAND is supposed to save stdin in the archive, if desired.
        rm $file
    else
        echo >&2 "$idtag err $COMMAND on file '$file' failed, moving to $FAILEDDIR"
        mv $file $FAILEDDIR
    fi
done

echo >&2 "$tag info $PROGRAM stopped"

