#! /bin/sh
#
# See usage below ...
#

LUOPT=""
AOPT=""
SOPT=""
TOPT=""
err=0
while /usr/bin/true; do
  case "x$1" in
  x-l)
    LUOPT="-l"
    shift
    ;;
  x-u)
    LUOPT="-u"
    shift
    ;;
  x-a)
    AOPT="-a"
    shift
    ;;
  x-s)
    SOPT="-s"
    shift
    ;;
  x-t)
    TOPT="$2"
    shift; shift;
    ;;
  x-*)
    err=1
    break
    ;;
  *)
    break
    ;;
  esac
done

if [ -z "$1" -o "$err" = 1 ]; then
  cat <<EOF
newdb [-l|-u][-a][-s][-t dbtype] dbfilenamebase [inputfile]
  A wrapper for   makedb  command, which does result file renameing
  in order to avoid need for LOCKING database files for compile time.
    -l/-u:     lower-/uppercasify the keys (default: no conversion)
    -a:        use alias rules
    -s:        be silent about result statistics
    -t dbtype: define what type of DB to use
         where dbtype is one of: btree bhash ndbm dbm gdbm
         see  makedb  for actually supported databases.
EOF
  exit 64
fi


BASENAME="$1"
INPUTNAME=${2:-$BASENAME}

ZCONFIG=/usr/local/etc/zmailer/zmailer.conf
. $ZCONFIG

PATH=/bin:/usr/bin:$PATH # ZMailer router paths are a bit restrictive..

trap "rm -f $BASENAME.$$*" 0

if [ -n "$TOPT" ]; then
  DBTYPE="$TOPT"
fi

$MAILBIN/makedb $LUOPT $AOPT $SOPT $DBTYPE $BASENAME.$$ < $INPUTNAME

case $? in
0)	;;
*)	x=$? ; echo '"'$BASENAME'" rebuilding aborted'
	rm -f $BASENAME.$$.*
	exit $x
	;;
esac

# Now install the files

case "$DBTYPE" in
btree)
	mv $BASENAME.$$.db $BASENAME.db
	;;
bhash)
	mv $BASENAME.$$.dbh $BASENAME.dbh
	;;
ndbm)
	mv $BASENAME.$$.dir $BASENAME.dir
	mv $BASENAME.$$.pag $BASENAME.pag
	;;
dbm)
	mv $BASENAME.$$.dir $BASENAME.dir
	mv $BASENAME.$$.pag $BASENAME.pag
	;;
gdbm)
	mv $BASENAME.$$.gdbm $BASENAME.gdbm
	;;
esac
