#!/usr/bin/perl -w

use strict;

#
# Adjustable parameters
#
my $srcdir = '/root/mp3';

#
# Retrieve the playlist
#
open(FH,"$srcdir/index") or die;
my @all = <FH>;
close FH;
chomp @all;

#
# Determine which track to play.
#
my $position = 0;
if (@ARGV) {
	$position = $ARGV[0] + 0;
} else {
	$position = rand @all;
}

#
# Terminate any other instances of player
#
my $my_pid = $$;
my @players = `ps ax|grep player.pl|grep -v grep|grep -v su|awk '{print \$1}'`;
chomp @players;
foreach (@players) {
	next if $_ == $my_pid;
	system "kill $_";
}
@players = `ps ax|grep madplay|grep -v grep|awk '{print \$1}'`;
chomp @players;
foreach (@players) {
	system "kill $_";
}
system "sleep 2";

#
# Main loop, play tracks in sequence
#
while ($position < @all) {
	system qq{madplay -Q "$srcdir/$all[$position]"};
	$position++;
}
