Here it is now. In this version the script behaves differently when a song is above a certain size
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use File::Copy;
#use Audio::MPD;
# Declaration of a few variables
my $musicdir = "/media/mp3/";
my $mountpoint = "/media/stick/";
my $sound_ok = $musicdir.'sounds/button16.wav';
my $sound_size = $musicdir.'sounds/subdive.wav';
my $sound_mount = $musicdir.'sounds/pfiff.wav';
my $threshhold = "150000000";
# Die if device is not added
if ($ENV{ACTION} =~ /remove/) { die };
# Device has to be mounted otherwise we don't get the freespace
system("mount", $mountpoint) == 0
or die system("aplay", "-q", "-d", "2", $sound_mount);
# Determine how much space in bytes is available
sub space {
my $space = `df $mountpoint`;
chop $space;
$space =~ /(\d+\s*)(\d+\s*)(\d+)\s*/mg;
my $free = $3 * 1024;
#print $free."\n";
return $free;
}
sub oldest {
my %data;
my @sorted;
my @content = `ls -1 $mountpoint`;
for (@content) {
chop $_;
$data{$_} = (stat($mountpoint.$_))[9];
@sorted = sort { $data{$a} cmp $data{$b} } keys %data;
}
#print Dumper \@sorted;
return shift(@sorted);
}
sub biggest {
my %data;
my @sorted;
my @content = `ls -1 $mountpoint`;
for (@content) {
chop $_;
$data{$_} = (stat($mountpoint.$_))[7];
@sorted = sort { $data{$a} cmp $data{$b} } keys %data;
}
return shift(@sorted);
}
die("MPD.pm not found!\n") unless -f "/usr/local/bin/MPD.pm";
require("/usr/local/bin/MPD.pm");
my $mpd = MPD->new();
my %currentsong = $mpd->get_current_song_info;
my $file = $musicdir.$currentsong{file};
my $filesize = (stat($file))[7];
#print "right before\n";
for (my $freespace = space(); $filesize > $freespace; $freespace = space()) {
#print "inside\n";
system("aplay", "-q", $sound_size);
if ($filesize > $threshhold) {
unlink($mountpoint.biggest()); #biggest() is the above function
} else {
unlink($mountpoint.oldest());
}
}
copy($file, "/media/stick")
or die "Copy failed: $!";
system("umount", $mountpoint);
system("aplay", "-q", $sound_ok);