#!/usr/bin/env perl 

use warnings;
use DBI;

use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock';
my $dbname   = 'nebulous';
my $dbserver = $ENV{NEB_DBSERVER};
my $dbuser = $ENV{NEB_USER};
my $dbpass = $ENV{NEB_PASS};
$db = DBI->connect("DBI:mysql:database=${dbname};host=${dbserver};" .
		   "mysql_socket=" . DB_SOCKET(),
		   ${dbuser},${dbpass},
		   { RaiseError => 1, AutoCommit => 1}
    ) or die "Unable to connect to database $DBI::errstr\n";

my $directory = shift(@ARGV);
$directory =~ s%/$%%;
system("neb-touch ${directory}/NEB_TREE_INTERNAL.$$");

my $dir_sth = "SELECT dir_id from storage_object where ext_id = '${directory}/NEB_TREE_INTERNAL.$$'";
# print "$dir_sth\n";
my $out;

$out = $db->selectall_arrayref( $dir_sth );
unless (defined( ${ ${ $out }[0] }[0])) {
    die "Directory $directory not found.\n";
}

system("neb-rm ${directory}/NEB_TREE_INTERNAL.$$");
    
$top_id = ${ ${ $out }[0] }[0];

my $subdir_sth = "SELECT dir_id from directory where parent_id = IDIDID";
my $object_sth = "SELECT ext_id from storage_object where dir_id = IDIDID";

@subdirectories = ($top_id);
do { 
    my $id = shift(@subdirectories);
    my $sd_sth = $subdir_sth;
    $sd_sth =~ s/IDIDID/$id/;
    my $ob_sth = $object_sth;
    $ob_sth =~ s/IDIDID/$id/;

    my $subdirs = $db->selectall_arrayref( $sd_sth );
    foreach my $rr (@{ $subdirs }) {
	push @subdirectories, ${ $rr }[0];
    }

    my $objects = $db->selectall_arrayref( $ob_sth );
    foreach my $rr (@{ $objects }) {
	print "${ $rr }[0]\n";
    }
    if ($#{ $objects } > -1) {
	print "\n";
    }
} while ($#subdirectories > -1);



