#! /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.

set -e

BOGOHOME=${1:-.}

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

# obtain list of database files
PAGES=0
DATABASES=`bogofilter -QQ -d "$BOGOHOME" | grep '^wordlist' | cut -f3 -d,`
if [ ! "$dbs" ] ; then
    echo >&2 "No database files in \"$BOGOHOME\" found"
    exit 1
fi

# count pages in database files
for DB in $DATABASES ; do
    COUNT=`bogoutil --db-print-leafpage-count="$DB"`
    let PAGES="$PAGES + $COUNT"
done

# be generous, double count
let PAGES="$PAGES + $PAGES"

# and update or create DB_CONFIG
: >> "$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 $PAGES
echo >>"$BOGOHOME"/DB_CONFIG.new set_lk_max_objects $PAGES
mv "$BOGOHOME"/DB_CONFIG.new "$BOGOHOME"/DB_CONFIG

# make change effective by recreating the environment
bogoutil --db-recover="$BOGOHOME"
