#!/usr/bin/perl
#dermixd-control: control DerMixD

#Copyright (c) 2005 Thomas Orgis (thomas@orgis.org)
#This is Open Source, Distribution and Modification under the terms of the Artistic License
#see the file LICENSE in the ThOrMA package root or at a place some steps upwards directory-wise if you got this file in a separate package

use strict;

use FindBin qw($Bin);
use lib $Bin.'/../lib/perl';
use lib $Bin.'/../lib/thorma/perl'; #we may operate withing ThOrMA
use lib $Bin.'/../lib/dermixd';

use Socket;
use Param;
use DerMixD::Control;

my $param = &Param::Parse
(
	{ 'init', "Simple script for sending mixplayd a command... \n Usage: $0 [options] command+arg\nThe script tries to be smart at start/seek/pause commands when no channel is given..." }
	,'remote','localhost','R','the (remote) server where dermixd is running on'
	,'verbose',0,'v','be more verbose about the server communication'
	,'silent',0,'s','do not even give a note on success'
	,'stay',0,'S','stay connected after commands have been issued (makes sense for scripting)'
	,'echo',0,'e','echo server responses verbatim to STDOUT (without this you will never see "[saying] Hello")',
	,'file',0,'f','read commands from files (scripts)',
	,'port',8888,'p','port number to connect to (where dermixd is listening)'
);

my $name = 'dermixd-control';
my $prompt = $name.'> ';

#first I simply died on error creating connection... that is not good for Web-frontend
#Thus, returned undef on error... that was somehow not consistent with my different perl versions (5.6 vs 5.8)
#so, now checking manually if there is a connection online

my $pal = new DerMixD::Control({'remote',$param->{remote},'debug',$param->{verbose},'echo',$param->{echo}, 'port', $param->{port}});
unless($pal->{online}){die "Not online ($!)\n";}

local(*DAT);

if(@ARGV)
{
	if($param->{file})
	{
		foreach my $f (@ARGV)
		{
			if(open(DAT, '<'.$f))
			{
				ScriptWork(\*DAT);
				close(DAT);
			}
			else{ print STDERR $name.': error opening '.$f."\n"; }
		}
	}
	else
	{
		DoWork(\@ARGV);
	}
}
else
{
	print STDERR "reading script from STDIN (no really fancy interactive shell yet)\n$prompt";
	ScriptWork(\*STDIN);
}

sub ScriptWork
{
	require Text::ParseWords;
	my $file = shift;
	while(<$file>)
	{
		if($_ =~ /^\s*([^#\s].*)$/)
		{
			#DoWork wants an array like @ARGV
			#I have a string that possibly contains quotes...
			#... for quoting spaces or as part of the data, gnnn.
			my @cl = Text::ParseWords::parse_line('\s+',0,$1);

			if(@cl)
			{
				my $com = $cl[0];
				DoWork(\@cl);
			}
			else{ print "$name: error parsing line\n"; }
		}
		if($pal->{online})
		{
			print "$prompt";
		}
		else
		{
			exit;
		}
	}
	print "\n";
}

sub DoWork
{
	my $bla = '';
	my $goingon = 1;
	
	my $arg = shift;
	if($arg->[0] eq 'wait')
	{
		shift(@{$arg});
		$goingon = 0;
		print "$name: error with wait meta-command\n" unless $pal->Wait($arg);
	}
	#search for files to load
	elsif($arg->[0] =~ /^(load|play)$/ and $param->{remote} eq 'localhost')
	{
		#arg->[1] is channel, arg->[2] is file
		my $last = $#{$arg};
		if(-e $arg->[$last])
		{
			unless($arg->[$last] =~ /^\//){ $arg->[$last] = $ENV{PWD}.'/'.$arg->[$last]; }
		}
		elsif(not $arg->[$last] =~ /^\S+:\/\//)
		{
			if( eval { require ThOrMA::Base; } ) #find first one in thorma archive, if present
			{
				print STDERR "Searching in ThOrMA\n";
				my $ff = ThOrMA::Base::FDSearch($arg->[$last],undef,undef,1);
				if($#{$ff} == -1)
				{
					print STDERR "No existing music file found for ".$arg->[$last]."! What to load?\n";
					$goingon = 0;
				}
				else{ $arg->[$last] = ThOrMA::Base::EnvEncode($ff->[0]); print STDERR "found $arg->[$last]\n"; }
			}
			else{ $goingon = 0; print STDERR "Cannot figure out what file you mean, sorry.\n"; }
		}
	}
	
	if($goingon)
	{
		my $e = $pal->Control($arg);
		unless($param->{silent}){print join("\n",@{$e})."\n";}
	}
}
