#!/usr/bin/perl
 
#
# - version 0.2 - 2008-12-08
#   * added --playpause to toggle status, use this option for your play-pause button
#   * support to play when stopped (was working only when was played
#
# - version 0.1
#   * initial release
#
 
 
#use strict;
use warnings;
use Audio::MPD;
use Getopt::Long;
 
my($mpdIp, $mpdPort, $mpdPass, $mpd);
$mpdIp = "localhost";
$mpdPort = 6600;
$mpdPass = "";
 
my %opt;
 
GetOptions(
	\%opt,
	"h|help"		=> \&usage,
	"i|ip=s"		=> \$mpdIp,
	"p|port=i"		=> \$mpdPort,
	"q|pass|password=s"	=> \$mpdPass,
	"play"			=> \&play,
	"pause"			=> \&pause,
	"fastforward|next"	=> \&fastforward,
	"rewind|previous"	=> \&rewind,
	"stop"			=> \&stop,
	"status"		=> \&status,
	"playpause"		=> \&playpause,
);
 
 
sub usage() {
	print "Usage: $0 [-h|--help] [-i|--ip ip] [-p|--port port] [-q|--pass|--password password] action\n";
	print "Action can be :\n";
	print "	[--play]\n";
	print "	[--pause]\n";
	print "	[--stop]\n";
	print "	[--fastforward|--next]\n";
	print "	[--rewind|--previous]\n";
	print "";
}
 
 
sub mpdConnect() {
	if($mpd) {
		return;
	}
	#print "$mpdIp:$mpdPort : $mpdPass\n";
	$mpd = Audio::MPD->new(hostname => $mpdIp,
				  port	   => $mpdPort,
				  password => $mpdPass);
}
 
sub play() {
	mpdConnect();
	$mpd->play();
}
 
sub pause() {
	mpdConnect();
	$mpd->pause();
}
 
sub fastforward() {
	mpdConnect();
	$mpd->next();
}
 
sub rewind() {
	mpdConnect();
	$mpd->prev();
}
 
sub stop() {
	mpdConnect();
	$mpd->stop();
}
 
sub status() {
	mpdConnect();
	return $mpd->status->state();
}
 
sub playpause() {
	$status = status();
	if($status eq "play") {
		pause();
	} else {
		play();
	}
}
 
exit 1;