#!/usr/bin/perl
#
# Expects a list of directories that contain ogg|flac
# Directories should be of the form: artist/album
# (i.e., not full paths or relative paths other than this)
#
# Changelog:
#   0.2.4: Initial release

$VERSION = "git";
$HELP_MSG = "# Copy files to DAP, converting flac to ogg v$VERSION\n\tusage: copy_top_dap artist1/album1 artist2/album2 ...";


use File::Path qw(make_path remove_tree);
use Cwd;

my $dest='/mnt/phone/music/';
my $tmpdir='/tmp/cp2dap/';



# Do we need help?
foreach (@ARGV)
{
    if (/^(--help)|(-h)$/) { die $HELP_MSG; }
}

# Abort if dest doesn't exist - its existence should be a prereq
die "Destination directory not found.  Is the DAP mounted?" unless -d $dest;

# Clean out any tmpdir cruft
remove_tree $tmpdir;


foreach (@ARGV)
{
    next unless (-d);

    # Are any of the files flac?
    my $has_flac;
    my @files = `ls $_`;
    foreach (@files)
    {
	chomp;
	if (/\.flac$/i)
	{
	    $has_flac = true;
	    break;
	}
    }

    # If we have flac, copy to tmpdir and convert first, then copy to
    # dest
    if ($has_flac)
    {
	make_path "$tmpdir/$_";
	make_path "$dest/$_";
	system("cp -r $_/* $tmpdir/$_/");
	system("conv2ogg $tmpdir/$_/*.flac");
	my $dir = cwd;
	chdir "$tmpdir/$_";
	system("tagfromfilename *");
	chdir $dir;
	system("cp -r $tmpdir/$_/* $dest/$_/");
    }
    else
    {
	make_path "$dest/$_";
	system("cp -r $_/* $dest/$_/");
    }

    undef $has_flac;
}

remove_tree $tmpdir;