#!/usr/bin/env perl

use strict;
use warnings;

use Nebulous::Key qw( parse_neb_key );
use Nebulous::Server;
use Nebulous::Server::Config;
use File::Basename qw( basename );

my $config = Nebulous::Server::Config->new(
    trace       => 'warn',
);
$config->add_db(
    dbindex     => 0,
    dsn         => 'DBI:mysql:database=nebulous:host=localhost',
    dbuser      => 'nebulous',
    dbpasswd    => '@neb@',
);

my $neb = Nebulous::Server->new_from_config($config);

my $db = $neb->_db_for_index(0);

my $n;
{
    my $query = $db->prepare("SELECT COUNT(*) as n FROM storage_object");
    $query->execute;
    $n = $query->fetchrow_hashref->{'n'};
}

my $query = $db->prepare_cached("SELECT so_id, ext_id, dir_id FROM storage_object AS so WHERE so.dir_id = 0 LIMIT 1000");

my $i = 0;
while ($query->execute and $query->rows) {
    print "foo\n";
    while (my $row = $query->fetchrow_hashref) {
        $i++;
        my $key = parse_neb_key($row->{'ext_id'});
        my $parent_id = $neb->_resolve_dir_parent_id(key => $key, create => 1);

#printf("dirizing %20s basename: %20s parent_id %10d\n", $key, basename($row->{'ext_id'}), $parent_id);
        printf("$i/$n dirizing %s\n", $key->path);

        my $q = $db->prepare_cached("UPDATE storage_object SET ext_id_basename = ?, dir_id = ? WHERE so_id = ?");
        $q->execute(basename($row->{'ext_id'}), $parent_id, $row->{'so_id'});
        $db->commit;
    }
    $query->finish;
}
