#!/bin/sh

#  bf_compact source_dir [wordlist_name...]
#
#    use to compact wordlist.db
#    replaces original directory with new one
#    renames original directory with '.old' extension

# $Id: bf_compact,v 1.14 2005/04/20 01:51:06 m-a Exp $

set -e # die on errors

if [ -z "$1" ] ; then
    echo usage: bf_compact source_dir [wordlist_name...]
    exit 1
fi

# extract home directory
BOGOHOME="$1"
shift

if [ ! -d $BOGOHOME ] ; then
    echo "$BOGOHOME must be a directory. Abort."
    exit 1
fi

# strip trailing slashes
while true; do
    case $BOGOHOME in
	*/) BOGOHOME=${BOGOHOME%/} ;;
	*)  break ;;
    esac
done

# find wordlist default
if [ -z "$1" ] ; then
    FILE=$(bogofilter -QQ -d "$BOGOHOME" | grep '^wordlist' | cut -f3 -d,)
else
    FILE="$@"
fi

TEMP="bf_compact.$$"

if ! mkdir "$TEMP" ; then
    echo "Cannot create directory $TEMP. Abort."
    exit 1
fi

# copy Berkeley DB configuration if present
if test -f "$BOGOHOME"/DB_CONFIG ; then
    cp -p "$BOGOHOME"/DB_CONFIG "$TEMP"/
fi

# determine transactions
trans=no
if test "$(find "$BOGOHOME/" -name "log.??????????" -print)" != "" ; then
    trans=yes
fi

# reload files
for j in $FILE ; do
    i=$(basename "$j")
    bogoutil -d "$BOGOHOME"/"$i" | bogoutil --db-transaction=$trans -l $TEMP/"$i"
done

#checkpoint and remove unneeded log files
bogoutil --db-prune=$TEMP

# remove $BOGOHOME.old so we don't move the new backup *into* it
# rather than renaming the backup to it.
rm -rf "$BOGOHOME.old"
mv "$BOGOHOME" "$BOGOHOME.old"
mv  $TEMP      "$BOGOHOME"
