#!/bin/sh

file=$1
backup=$1.txt
oldbackup=$1.txt.old
if [ -z "$DB_VERSION" ]; then
  # Version in Debian "sarge"
  version=4.2
else
  version=$DB_VERSION
fi
if [ "$file" = "" ]; then
    echo "Usage: $0 file"
    exit 1
fi

if [ ! -e $file ]; then
    echo "$file does not exist"
    exit 1
fi

if `db${version}_verify -q $file`; then
    true
else
    echo "Invalid file, not backuping"
    exit 1
fi

num=`db${version}_stat -d $file | awk '/Number of keys in the database/ {print $1}'`
if [ ! -e $backup ]; then
    echo "h_nelem=0" > $backup
fi
oldnum=`awk -F= '/h_nelem/ {print $2}' $backup`
if [ -z "$oldnum" ]; then
   oldnum=0
fi
if test $num -lt $oldnum; then
    echo "Less entries than the backup, not backuping"
    exit 1
fi

if test "$oldnum" = ""; then
    echo "Empty backup, not copying it"
else
    cp $backup $oldbackup
    gzip --force --quiet --best $oldbackup
fi
db${version}_dump $file > $backup
