#! /bin/sh
#
# -*-sh-*-
#
#     Copyright (C) 1999-2018  Roland Rosenfeld <roland@spinnaker.de>
#     Copyright (C) 2007       Yaroslav Halchenko <debian@onerussian.com>
# 
#     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; if not, write to the Free Software Foundation,
#     Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,, USA.

LBDB_VERSION=0.48

umask 077

prefix=/usr/pkg
exec_prefix=${prefix}
dotlock=${exec_prefix}/bin/lbdb_dotlock
db=$INMAIL_DB
munge=/usr/pkg/lib/../libexec/lbdb/munge

if [ ! -f $db.dirty ]
then
    # Nothing to do
    exit 0
fi

if [ "$SORT_OUTPUT" = "false" -o "$SORT_OUTPUT" = "no" ]
then
    munge_options="keeporder=1"
fi

if [ -z "$MUNGE_LIMITCOUNT" ]
then
    munge_options="$munge_options limitcount=1"
else
    munge_options="$munge_options limitcount=$MUNGE_LIMITCOUNT"
fi

if [ ! -z "$MUNGE_LIMITDATE" ]
then
    munge_options="$munge_options limitdate='$MUNGE_LIMITDATE'"
fi

if $dotlock -r 10 -f $db
then
    : # okay, do nothing
else
    echo "Can't lock $db [dotlock returned $?]." >&2
    exit 1
fi

if $munge ${munge_options} < $db > $db.$$.tmp
then
    # only move, if munge successful:
    mv -f $db.$$.tmp $db
    rm -f $db.dirty
else
    rm -f $db.$$.tmp
    # maybe write a debug log here...
fi

$dotlock -u $db
