#!/usr/bin/perl
use strict;
use warnings;
use File::Basename;

my $dir=getDir();

my $newFile=getNewestFile($dir);
die if $newFile eq '';
my $workDir=`echo ~/Music`;
chomp $workDir;
-d $workDir or mkdir $workDir;

$workDir.='/'.getDate();
-d $workDir or mkdir $workDir;
my $from="$dir/$newFile";
my $to="$workDir/$newFile";
-f $to or stageFile($from,$workDir);

my $toDir=mkTarget($workDir);
processFile($workDir,$toDir);


chdir $workDir or die "could not cd to $workDir";
my $fm="/usr/bin/nautilus";

sub getDir {
    my @dirs=`ls -dh /media/[0-9]*`;
    foreach my $dir (@dirs) {
	chomp $dir;
	if($dir=~/\/\d*/) {
	    $dir.="/STEREO";
	    -d $dir or die "$dir";
	    my @folders=`ls -dt $dir/FOLDER??`;
	    my $folder=$folders[0];
	    chomp $folder;

	    -d $folder or die "$folder";
	    printf "found $folder\n";
	    return $folder;
	}
	die "no SD card found" unless $dir and -d $dir;
    }
    die "no SD card found";
}

sub getNewestFile {
    #To do: getNewestFiles, in case more than one in last 24h.
    my @fil=`ls -t $dir/*WAV`; #idiofact of H4n
    my $file=shift;
    chomp $file;
    die "$file" unless -f $file;
    printf "Found $file\n";
    return $file;
}

sub getDate {
    #To do: this needs to check file time.  If midnight<now<noon, 
    #then use date math module to decrement date.  Otherwise, do this:
    my $d=scalar localtime;
    my @bits=split / /, $d;
    my $hotDate=sprintf "%02d%3s%04d", $bits[2],$bits[1],$bits[4];
    printf "Album: $hotDate\n";
    return $hotDate;
}

sub stageFile {
    my $file=shift;
    my $workDir=shift;
    #To do: handle multiple files
    my $cmd=sprintf "/bin/cp -p %s %s 2>&1 ", $file, $workDir;
    printf "%s\n", $cmd;
    #To do: pluck filename from end o' path, find increments if they exist. 
    #This assumes H4n uses correct naming convention and has correct date.
    #/bin/cp -p /media/6264-6333/STEREO/FOLDER01/130322-000.wav /home/e3/Music/23Mar2013 2>&1 
    my $result=`$cmd`;
    die $result if $result;
}

sub processFile {
#This needs a hash or array ref to a list of input files, and it needs 
#the album title to name the output.  
    my $from=shift;
    -d $from or die "$from not found yo";

    my $to=shift;
    -d $to or die "$to not found yo";

    my $cmd=sprintf "/usr/bin/sox %s/*wav %s/%s.wav", $from,$from,$to;
    system($cmd) or die "$cmd";

    $cmd=sprintf "/usr/bin/audacity %s", $to;
    system($cmd) or die "$cmd";
}

sub getScreenShot {
    my $doit="/usr/bin/gnome-screenshot";
    my @results=`$doit`;
}

sub mkTarget {
    #Typically, audacity would have created target dir already. 
    my $target='/media/LaCie/e3/Music/';
    -d $target or die "$target not found";

    my $album=shift;
    $album=basename($album);
    $target.="$album.mp3";
    -d $target or mkdir $target;
    -d $target or die "$target not found";
    return $target;
}
