#!/usr/bin/perl -T

use Test::More tests => 12;
use Paranoid;
use Paranoid::Debug;
use Paranoid::BerkeleyDB::Env;
use Paranoid::BerkeleyDB::Db;

use strict;
use warnings;

psecureEnv();

my ( $rv, $dbe, $db, $adb, $pid, $prv );

mkdir './t/db';

#PDEBUG = 20;

# Create a db with no environment
$db = new Paranoid::BerkeleyDB::Db;
ok( !defined $db, 'invalid invocation - 1' );
$db = new Paranoid::BerkeleyDB::Db '-Filename' => 't/db/test.db';
ok( defined $db, 'valid invocation - 2' );

$adb = new Paranoid::BerkeleyDB::Db '-Filename' => 't/db/test.db';
ok( defined $adb, 'duplicate handle - 3' );
is( $adb->db, $db->db, 'duplicate handle - 4' );

$rv = $db->db;

# Test fork
if ( $pid = fork ) {
    wait;
    $prv = $?;
} else {
    $prv =
        (      ( $rv != $db->db )
            && ( $rv != $adb->db )
            && ( $db->db == $adb->db ) ) ? 0 : 1;
    exit $prv;
}
is( $prv, 0, 'forked database checks - 5' );

# Close databases
$db = $adb = $rv = undef;
system 'rm t/db/*';

# Open an environment and reopen with it
$dbe = new Paranoid::BerkeleyDB::Env '-Home' => 't/db';
ok( defined $dbe, 'created environment - 6' );

#PDEBUG=20;
$db = new Paranoid::BerkeleyDB::Db
    '-Filename' => 'cdb.db',
    '-Env'      => $dbe;
ok( defined $db, 'env invocation - 7' );
is( $db->env, $dbe, 'env confirmation - 8' );

$adb = new Paranoid::BerkeleyDB::Db
    '-Filename' => 'cdb.db',
    '-Env'      => $dbe;
ok( defined $adb, 'duplicate handle - 9' );
is( $adb->env, $dbe,    'env confirmation - 10' );
is( $adb->db,  $db->db, 'duplicate handle - 11' );

$rv = $db->db;
my $erv = $dbe->env;

# Test fork
#PDEBUG = 20;
if ( $pid = fork ) {
    wait;
    $prv = $?;
} else {
    $prv =
        (      ( $rv != $db->db )
            && ( $rv != $adb->db )
            && ( $erv != $dbe->env )
            && ( $db->db == $adb->db ) ) ? 0 : 1;
    exit $prv;
}
is( $prv, 0, 'forked database checks - 12' );

# Cleanup
system 'rm -rf t/db';

