#!/usr/bin/perl
###########################################
# topod
# Mike Schilli, 2003 (m@perlmeister.com)
###########################################
use warnings;
use strict;

my $POD_DIR = "/ms1/SONGS/pods";

use File::Basename;
use Algorithm::Bucketizer;
use File::Copy;

my %seen = ();

    # Init buckets
my $b = Algorithm::Bucketizer->new(
    bucketsize => 700_000_000,
    algorithm  => 'simple',
);

    # Prefill buckets with existing Pods
while(<$POD_DIR/*>) {
    my($idx) = /(\d{3})/;

    while(<$POD_DIR/$idx/*.mp3>) {
        my $base = basename($_);
        if(exists $seen{$base}) {
            print "Dupe detected: $_\n";
        }
        $seen{$base}++;
        $b->prefill_bucket($idx - 1, 
                           $_, -s $_);
    }
}

while(<*.mp3>) {
    if(exists $seen{$_}) {
        print "Not adding dupe: $_\n";
        next;
    }

    $seen{$_}++;

    my $bucket = $b->add_item($_, -s $_);

    my $path = sprintf "$POD_DIR/%03d/$_", 
                      $bucket->serial();

    unless(-d dirname($path)) {
        mkdir dirname($path) or 
            die "Cannot mkdir " . 
                dirname($path);
    }

    move($_, $path) or 
        die "Cannot move $_ to $path";