#! @PERL@
#
# See usage below ...
#
# FIXME: input file owner/protection should be copied to the db file!
#

# use strict 'vars';

use Getopt::Std;

$LUOPT = '';
$AOPT  = '';
$SOPT  = '';
$TOPT  = '';
$err   = 0;

%opts = ();
%ZENV = ();

if (!getopts('alsut:', \%opts) || !defined($ARGV[0])) {

    printf(STDERR "
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.
");
  exit 64;
}

$AOPT  = '-a' if (defined $opts{'a'});
$LUOPT = '-l' if (defined $opts{'l'});
$LUOPT = '-u' if (defined $opts{'u'});
$SOPT  = '-s' if (defined $opts{'s'});
$TOPT  = $opts{'t'} if (defined $opts{'t'});

$BASENAME  = $ARGV[0];
$INPUTNAME = $BASENAME;
$INPUTNAME = $ARGV[1] if ($ARGV[1]);

& pick_zenv();

$MAILBIN = $ZENV{'MAILBIN'};

# ------------------

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

if ( "$TOPT" ) {
  $ZENV{'DBTYPE'}="$TOPT"
}

$DBTYPE = $ZENV{'DBTYPE'};

if (system("$MAILBIN/makedb $LUOPT $AOPT $SOPT $DBTYPE $BASENAME.$$ < $INPUTNAME")) {
	$err = $!;
	printf("'$BASENAME' rebuilding aborted\n");
	system("rm -f $BASENAME.$$.*");
	exit $err;
}

# Now install the files


if ($DBTYPE eq 'btree') {
	system("mv $BASENAME.$$.db $BASENAME.db");
} elsif ($DBTYPE eq 'bhash') {
	system("mv $BASENAME.$$.dbh $BASENAME.dbh");
} elsif ($DBTYPE eq 'ndbm') {
	system("mv $BASENAME.$$.pag $BASENAME.pag"); # First PAG, then DIR
	system("mv $BASENAME.$$.dir $BASENAME.dir");
} elsif ($DBTYPE eq 'dbm') {
	system("mv $BASENAME.$$.pag $BASENAME.pag"); # First PAG, then DIR
	system("mv $BASENAME.$$.dir $BASENAME.dir");
} elsif ($DBTYPE eq 'gdbm') {
	system("mv $BASENAME.$$.gdbm $BASENAME.gdbm");
}

exit 0;


# --------------------

sub pick_zenv {

    my ($ZCONFIG) = '@ZMAILERCFGFILE@';

    open(ZZ, "< ".$ZCONFIG) || die "No ZCONFIG file at '$ZCONFIG'";
    while (<ZZ>) {
	chomp;
	local($n,$l) = split(/=/,$_,2);
	$ZENV{$n} = $l  if ($n =~ m/^[A-Z0-9a-z]/);
    }
    close(ZZ);
}


1;
