%
% launch Linda server & clients
%

:- use_module(library(system)).
:- use_module(library(lists)).
:- use_module('../prolog/util/flatten').
:- use_module('../prolog/util/cmdline').

%
% the starting predicate
%
go :-
	(	(	cmdline:get_command_line('-lp',Port),	%try to get the '-lp' command line
			!
		);
		Port=_						%if '-lp' isn't found
	),
	(	cmdline:get_command_line('-c',Config);		%looking for command-line '-c'
		Config='launcher.config'
	),
	go(Config,Port).


%
% launch with the specifc config file
%
go(Config,Port) :-
		reconsult(Config),
		server(Server),			%get server command-line
		findall(X,client(X),Clients),	%get all client command-lines
		launch(Server,Clients,Port),	%launch server & clients
		halt.

launch(Server,Clients,Port) :-
	name(Server,Server_in_string),
	compose_clients_string(Clients,Clients_in_string),
	(	(	nonvar(Port),					%if port is specified
			name(Port,Port_in_string),
			flatten([	Server_in_string,
					" -lp ",
					Port_in_string,
					" ",
					Clients_in_string,		%get it all client command-lines
					"&"
				],Command_in_string)
		);
		(	var(Port),					%if no port is specified
			flatten([	Server_in_string,
					" ",
					Clients_in_string,		%get it all client command-lines
					"&"
				],Command_in_string)
		)
	),
	name(Command,Command_in_string),		%convert string into atom
	system(Command).				%invoke xterm & start server

compose_clients_string([Command],String) :-
	name(Command,Command_in_string),
	flatten([	"-cl \'",
			Command_in_string,
			"\'"
		],String),
	!.

compose_clients_string([Command|Clients],String) :-
	name(Command,Command_in_string),
	flatten([	"-cl \'",
			Command_in_string,
			"\'"
		],S1),
	compose_clients_string(Clients,S2),
	flatten([S1," ",S2],String).


%
% auto-start after loading
%
:- go.

