#!/usr/bin/perl
########################################################################
# MP3launch - A wrapper for starting XMMS with playlist files
# as arguments
#
# Copyright (C) 1999 Sami Lempinen
# See the file COPYING for copyright and warranty information.
########################################################################
$VERSION = substr(q$Revision: 1.7 $, 10);
$| = 1; # Force flush after each system ()
use Getopt::Std; # For command line parsing

getopts ('vh');

# Check if we received any arguments
if ($#ARGV < 0 || $opt_h) 
{
    Usage ();
    exit -1;
}

$VERBOSE = $opt_v;
$songcount = 0;

while ($#ARGV >= 0) 
{
    $playlist = shift;
    # Check if the playlist file is readable
    if (! -r $playlist) 
    {
	print STDERR "$playlist is not readable. Ignoring.\n";
    } 
    else 
    {
	print "* Adding playlist $playlist\n" if ($VERBOSE);
	# Open the playlist
	open (PLAYLIST, $playlist) || next;
	# Iterate through each line in the list
	while ($song = <PLAYLIST>) 
	{
	    chop $song;
	    # Check if the song is readable
	    if (! -r $song) 
	    {
		print STDERR "\t$song not playable. Ignoring.\n";
	    } 
	    else 
	    {
		print "\tAdding $song\n" if ($VERBOSE);
		$song = Secure ($song);

		push (@songlist, $song);
		$songcount++;
	    }
	}
	
	$ampCmd = "xmms ".join(' ', @songlist)." &";
	
	print "Spawning XMMS..." if ($VERBOSE);
	$success = system ($ampCmd);
	if ( $success == 0) 
	{
	    print "done.\n" if ($VERBOSE);
	} 
	else 
	{
	    print "failed. Check that the xmms executable ",
	    "is in your \$PATH.\n" if ($VERBOSE);
	}
    }
}


# A subroutine for making the song names shell secure
sub Secure 
{
    my $name = shift;

    $name =~ s/\'/\\\'/g; # Escape single quotes
    $name =~ s/\(/\\\(/g; # Parenthesis
    $name =~ s/\)/\\\)/g; # Parenthesis
    $name =~ s/\ /\\\ /g; # Spaces (thanks to Kjetil Thuen)
    $name =~ s/\&/\\\&/g; # Ampersands
    $name =~ s/\>/\\\>/g; # Larger than
    $name =~ s/\</\\\</g; # Less than
    $name =~ s/\]/\\\]/g; # Right bracket
    $name =~ s/\[/\\\[/g; # Left bracket
    return $name;
}

# Help and copyright information
sub Usage 
{
    print <<EOT;

* MP3launch $VERSION Copyright (C) 1999 Sami Lempinen
* A wrapper for starting XMMS with playlist files as arguments

MP3launch comes with ABSOLUTELY NO WARRANTY; for details see the file COPYING.
This is free software, and you are welcome to redistribute it
under certain conditions; for details see the file COPYING.

  Usage: mp3launch playlist-file [playlist-file ...]

      -v         Verbose mode
      -h         This help screen

EOT
}

