# Copyright (C) 2004  Joshua Hoblitt
#
# $Id: Nebulous.pm,v 1.15 2007-05-04 23:36:46 jhoblitt Exp $

package Test::Nebulous;

use strict;

use DBI;
use File::Path qw( mkpath rmtree );
use File::Temp qw( tempdir );
use Nebulous::Server::SQL;

my $dsn     = "DBI:mysql:database=test:host=localhost";
my $user    = "test";
my $passwd  = "";

my $dbh = DBI->connect( $dsn, $user, $passwd );
my $sql = Nebulous::Server::SQL->new;

# suppress uninitalized warnings
my $dir1 = "";
my $dir2 = "";
my $dir3 = "";
my $dir4 = "";
my $dir5 = "";
my $dir6 = "";

sub setup {
    my $self = shift;

    $self->cleanup;

    # create directories after cleanup
    $dir1 = tempdir( CLEANUP => 0 );
    $dir2 = tempdir( CLEANUP => 0 );
    $dir3 = tempdir( CLEANUP => 0 );
    $dir4 = tempdir( CLEANUP => 0 );
    $dir5 = tempdir( CLEANUP => 0 );
    $dir6 = tempdir( CLEANUP => 0 );

    foreach my $statement (@{ $sql->get_db_schema }) {
        $dbh->do( $statement );
    }

    # node01/node02: allocate = TRUE
    $dbh->do(qq{ INSERT INTO volume (vol_id, name, path, allocate, available) VALUES (1, 'node01', ?, TRUE, TRUE) }, undef, $dir1);
    $dbh->do(qq{ INSERT INTO mount VALUES (?, 10e10, 10e7) }, undef, $dir1);

    $dbh->do(qq{ INSERT INTO volume (vol_id, name, path, allocate, available) VALUES (2, 'node02', ?, TRUE, TRUE) }, undef, $dir2);
    $dbh->do(qq{ INSERT INTO mount VALUES (?, 10e10, 10e8) }, undef, $dir2);

    # node03: allocate = TRUE, volume full
    $dbh->do(qq{ INSERT INTO volume (vol_id, name, path, allocate, available) VALUES (3, 'node03', ?, TRUE, TRUE) }, undef, $dir3);
    $dbh->do(qq{ INSERT INTO mount VALUES (?, 10e10, 10e10) }, undef, $dir3);

    # node04: allocate = FALSE, available = FALSE
    $dbh->do(qq{ INSERT INTO volume (vol_id, name, path, allocate, available) VALUES (4, 'node04', ?, FALSE, FALSE) }, undef, $dir4);
    $dbh->do(qq{ INSERT INTO mount VALUES (?, 10e10, 10e7) }, undef, $dir4);

    # node05: allocate = FALSE, available = TRUE
    $dbh->do(qq{ INSERT INTO volume (vol_id, name, path, allocate, available) VALUES (5, 'node05', ?, FALSE, TRUE) }, undef, $dir5);
    $dbh->do(qq{ INSERT INTO mount VALUES (?, 10e10, 10e7) }, undef, $dir5);

    # node06: allocate = TRUE, available = FALSE
    $dbh->do(qq{ INSERT INTO volume (vol_id, name, path, allocate, available) VALUES (6, 'node06', ?, TRUE, FALSE) }, undef, $dir4);
    $dbh->do(qq{ INSERT INTO mount VALUES (?, 10e10, 10e7) }, undef, $dir6);

    $dbh->do(qq{ call getmountedvol() });
}

sub cleanup {
    foreach my $statement (@{ $sql->get_db_clear }) {
        $dbh->do( $statement );
    }

    # on the first call to setup the $dir[12] will be ""
    rmtree([$dir1], 0, 1) if -e $dir1;
    rmtree([$dir2], 0, 1) if -e $dir2;
    rmtree([$dir3], 0, 1) if -e $dir3;
    rmtree([$dir4], 0, 1) if -e $dir4;
    rmtree([$dir5], 0, 1) if -e $dir5;
    rmtree([$dir6], 0, 1) if -e $dir6;
}

1;

__END__
