#!/usr/bin/env perl

use strict;
use List::Util 'shuffle';

my $size = 230;

sub usage() {
	printf("Usage: randommp3 <sourcedir> <targetdir> [size]\n");
	printf("copies up to size mb of random mp3's from sourcedir to targetdir\n");
	printf("Defaults to 230 mb\n");
	exit();
}

my $sourcedir = shift();

if (!$sourcedir) {
	usage();
}

my $targetdir = shift();

if (!$targetdir) {
	usage();
}

my $newsize = shift();
if ($newsize) {
	$size = $newsize;
}

my @all_mp3_files = `find $sourcedir -name \*.mp3`;

#print @all_mp3_files;

my @shuffled = shuffle(@all_mp3_files);

my $current = shift(@shuffled);
my $totalsize = 0;
my @to_copy = ();

while ($current && $totalsize < $size * 1024 * 1024) {
	#$current =~ s/ /\\ /g;
	chomp($current);
	#print "ls -l '$current'\n";
	my $cfile = `ls -l '$current'`;
	#print $cfile;
	if ($cfile =~ /.+\s+[0-9]+\s+\w+\s+\w+\s+([0-9]+).*/) {
		$totalsize += $1;
		if ($totalsize < $size * 1024 * 1024) {
			push(@to_copy, $current);
		}
	}
	$current = shift(@shuffled);
}

foreach my $copy (@to_copy) {
	my $cmd = "cp '$copy' '$targetdir'";
	my $result = system($cmd);
	if ($result != 0) {
		print "Error! $result\n";
		exit($result);
	}
}
