#! /bin/sh

# (C) 2004 Matthias Andree, GNU GPL v2
#
# This script, bf_resize, tries to guess useful sizes for the lock
# environment.

# Usage: bf_resize [DIR]
#   DIR defaults to . and is the path of a bogofilter Berkeley database
#   environment.
#
# This script reads all databases in that directory, calculates a lock
# size and writes it to DB_CONFIG, then runs recovery to make the change
# effective.

# environment overrides:
#   DB_ARCHIVE	- path to db_archive to use
#   AWK		- path to awk to use

set -e

BOGOHOME=${1:-.}

if [ ! -d $BOGOHOME ] ; then
    echo "$BOGOHOME" must be a directory, not a file
    exit
fi

: ${DB_ARCHIVE:=db_archive}
: ${AWK:=awk}

a=0
dbs=$(db_archive -s -a -h "$BOGOHOME")
if [ ! "$dbs" ] ; then
    echo >&2 "No database files in \"$BOGOHOME\" found"
    exit 1
fi

for i in $dbs ; do
    pages=$(db_stat -h "$BOGOHOME" -d "$i" \
	    | awk '/Number of tree leaf pages/ {print $1;}')
    a=$(( $a + $pages ))
done

# be generous
a=$(( $a * 2 ))

touch "$BOGOHOME"/DB_CONFIG
(
  set +e
  egrep -v '^set_lk_max_(locks|objects)' "$BOGOHOME"/DB_CONFIG >"$BOGOHOME"/DB_CONFIG.new
)
if [ $? -ge 2 ] ; then exit 1 ; fi
echo >>"$BOGOHOME"/DB_CONFIG.new set_lk_max_locks $a
echo >>"$BOGOHOME"/DB_CONFIG.new set_lk_max_objects $a
mv "$BOGOHOME"/DB_CONFIG.new "$BOGOHOME"/DB_CONFIG
bogoutil --db-recover="$BOGOHOME"
