#!/usr/bin/perl

# Author: tomekk                                                                                                                                                                         
# e-mail:  tomekk/@/oswiecim/./eu/./org                                                                                                                                                  
# home page: http://tomekk.oswiecim.eu.org/
#
# Version 0.1
#
# This file is Copyrighted under the GNU Public License.
# http://www.gnu.org/copyleft/gpl.html
##########################################################

# some uses
use IO::Socket;
use Proc::Daemon;
use Proc::PID::File;
Proc::Daemon::Init; # comment this line for debug

# local address 
$listen_address = "192.168.0.1";

# local port
$listen_port = 1234;

# xmms unix socket path (default: /tmp/xmms_user.id)
$xmms_socket_path = "/tmp/xmms_tomekk.0";

# xmms file with song name (provided by 'Song Change' xmms plugin [plugin included in xmms])
$xmms_song_file = "/tmp/xmms_song.txt";

##########################################################
$server_socket = IO::Socket::INET->new(LocalAddr => $listen_address, LocalPort => $listen_port, Proto => 'tcp', Listen => 5, Reuse => 1) or die "cannot open tcp socket ($listen_address - $listen_port)";

# send cmd to the xmms unix socket
sub xmms_cmd 
{
	($cmd) = @_;

	$xmms_socket = IO::Socket::UNIX->new(Peer => $xmms_socket_path, Type => SOCK_STREAM) or die "cannot open $xmms_socket_path";
	print $xmms_socket pack("SSI", 1, $cmd, length($cmd)) or die "cannot write to the unix socket";
	$xmms_socket->close;
}

# main loop
while(1)
{
	$client_socket = $server_socket->accept();

	print $client_socket "ready\n";
	
	# do some things with remote commands
	# switch switch ohh noes... let's do if-s ;p (better compatibility)
	while ($client_cmd = <$client_socket>)
	{
		chomp($client_cmd);

		# wee need just simple commands
		if ($client_cmd eq "play") {
			xmms_cmd (2);
			print $client_socket "ok\n";
		} elsif ($client_cmd eq "pause") {
			xmms_cmd (3);
			print $client_socket "ok\n";
		} elsif ($client_cmd eq "stop") {
			xmms_cmd (4);
			print $client_socket "ok\n";
		} elsif ($client_cmd eq "prev") {
			xmms_cmd (29);
			print $client_socket "ok\n";
		} elsif ($client_cmd eq "next") {
			xmms_cmd (30);
			print $client_socket "ok\n";
		} elsif ($client_cmd eq "song") {
			# get song title from the file 'generated' by 'Song Change' plugin
			if (open (SONG_FILE, "<$xmms_song_file"))
			{
				$song = <SONG_FILE>;
				print $client_socket $song;
				close (SONG_FILE);
			} else {
				print $client_socket "cannot open $xmms_song_file\n";
			}
		}
	}
}

close($server_socket);
