(* ::Package:: *)

BeginPackage[ "AdditiveCluster`", {"SubKernels`RemoteKernels`"} ]

LaunchClusterKernels::usage = "LaunchClusterKernels[clusterModule_String, nKernelsNode_Integer] loads the module 'clusterModule' on any node in the Job and starts 'nKernelsNode' Mathematica-Kernels on each node."

Begin[ "Private`" ]

ConfigureSSHKernels[clusterModule_String, machine_String, username_String, numberOfKernels_Integer]:=
	Module[
		{ssh, math, remote},
		Parallel`Settings`$MathLinkTimeout=100;
		ssh="ssh";
		math=clusterModule<>"; MathKernel"<>" -wstp -linkmode Connect `4` -linkname `2` -subkernel -noinit >& /dev/null &";
		remote=SubKernels`RemoteKernels`RemoteMachine[machine,ssh<>" "<>username<>"@"<>machine<>" "<>" \""<>math<>"\"",numberOfKernels];
		Print[remote//InputForm];
		remote
];

LaunchClusterKernels[clusterModule_String,nKernelsNode_Integer]:=
	Module[
		{nodes, kernels},
		nodes=DeleteCases[StringSplit[Environment["SLURM_JOB_NODELIST"],"&"], $MachineName];
		kernels=Map[LaunchKernels[ConfigureSSHKernels[clusterModule,#,$UserName,nKernelsNode]]&,nodes];
		kernels
];

End[]

EndPackage[]

