#!/bin/sh

#  db_copy [-c] source_dir dest_dir
#
#    use to copy wordlist.db and related files
#    from one directory to another

# $Id: bf_copy,v 1.4 2004/11/25 22:29:50 relson Exp $

set -e # die on errors

COMPACT=0
while test "$1" ; do
    case "$1" in
	-c) COMPACT=1 ;;
	-*) echo "unknown option $1" >&2 ; exit 1 ;;
	*) break;
    esac
    shift
done

if [ $# -ne 2 ] ; then
    echo usage: db_copy [-c] source_dir dest_dir
    echo "   use -c to copy active logs, not all"
    exit 1
fi

SRC="$1"
DST="$2"

# flush mempools
db_checkpoint -1h "$SRC" || :

mkdir "$DST"

TMP=bfc.$$.unneeded
rm -f $TMP
trap "rm -rf $TMP \"$DST\"" 0
if test $COMPACT -eq 1 ; then
  # don't copy unneeded logs
  db_archive -h "$SRC" >$TMP
else
  : >$TMP
fi
LOGS=`ls "$SRC"/log.* | grep -v -F -f $TMP`
if test "$LOGS" ; then cp -p $LOGS "$DST" ; fi
ENV=`ls "$SRC"/__db.* || :`
if test "$ENV" ; then cp -p $ENV "$DST" ; fi
if test -f "$SRC"/DB_CONFIG ; then cp -p "$SRC"/DB_CONFIG "$DST" ; fi

for FILE in "$SRC"/*.db ; do
    NAME=`basename $FILE`
    SIZE=`db_stat -h "$SRC" -d $NAME | awk '/page size/ {print $1}'`
    dd bs=$SIZE if="$FILE" of="$DST/"`basename "$FILE"`
done

db_recover -h "$DST"
rm -f $TMP
trap - 0
