/*
 *   Copyright 2010 Brian Rosenberger (Brutex Network)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package net.brutex.xservices.ws.impl;

import java.io.File;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import net.brutex.xservices.types.HostConnection;
import net.brutex.xservices.types.ReturnCode;
import net.brutex.xservices.util.BrutexNamespaces;
import net.brutex.xservices.util.RunTask;
import net.brutex.xservices.ws.ExecuteService;
import net.brutex.xservices.ws.XServicesFault;

import org.apache.tools.ant.taskdefs.ExecTask;
import org.apache.tools.ant.taskdefs.optional.net.RExecTask;
import org.apache.tools.ant.taskdefs.optional.net.TelnetTask;
import org.apache.tools.ant.taskdefs.optional.ssh.SSHExec;
import org.apache.tools.ant.types.Commandline;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

/**
 * 
 * @author Brian Rosenberger, bru@brutex.de
 */
@WebService(targetNamespace = BrutexNamespaces.WS_XSERVICES, endpointInterface = "net.brutex.xservices.ws.ExecuteService", serviceName = "ExecuteService")
public class ExecuteServiceImpl implements ExecuteService {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runCommand(java.lang.String,
	 * java.lang.String, long)
	 */
	@WebMethod(operationName = "runCommand")
	public ReturnCode runCommand(@WebParam(name = "executable") String cmd,
			@WebParam(name = "argline") String args,
			@WebParam(name = "timeout") long timeout) {

		return executeCommand(cmd, Commandline.translateCommandline(args),
				null, false, null, false, true, false, timeout);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runCommandWithArgs(java.lang
	 * .String, java.lang.String[], long)
	 */
	
	@WebMethod(operationName = "runCommandWithArgs")
	public ReturnCode runCommandWithArgs(
			@WebParam(name = "executable") String cmd,
			@WebParam(name = "arg") String[] args,
			@WebParam(name = "timeout") long timeout) {

		return executeCommand(cmd, args, null, false, null, false, true, false,
				timeout);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runCommandAsync(java.lang
	 * .String, java.lang.String)
	 */
	
	@WebMethod(operationName = "runCommandAsync")
	public ReturnCode runCommandAsync(
			@WebParam(name = "executable") String cmd,
			@WebParam(name = "argline") String args) {

		return executeCommand(cmd, Commandline.translateCommandline(args),
				null, true, null, false, true, false, 0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runCommandAsyncWithArgs(java
	 * .lang.String, java.lang.String[])
	 */
	
	@WebMethod(operationName = "runCommandAsyncWithArgs")
	public ReturnCode runCommandAsyncWithArgs(
			@WebParam(name = "executable") String cmd,
			@WebParam(name = "arg") String[] args) {

		return executeCommand(cmd, args, null, true, null, false, true, false,
				0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runCommandWithSSH(java.lang
	 * .String, int, java.lang.String, java.lang.String, java.lang.String, long)
	 */
	
	@WebMethod(operationName = "runCommandWithSSH")
	public ReturnCode runCommandWithSSH(
			@WebParam(name = "host") HostConnection host,
			@WebParam(name = "command") String cmd,
			@WebParam(name = "timeout") long timeout) {

		return sshExec(host.hostname, host.user, host.password, host.port, cmd,
				timeout);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runCommandWithSSHKeyAuth(
	 * java.lang.String, int, java.lang.String, java.lang.String,
	 * java.lang.String, java.lang.String, long)
	 */
	
	@WebMethod(operationName = "runCommandWithSSHKeyAuth")
	public ReturnCode runCommandWithSSHKeyAuth(
			@WebParam(name = "host") HostConnection host,
			@WebParam(name = "keyfile") String keyfile,
			@WebParam(name = "command") String cmd,
			@WebParam(name = "timeout") long timeout) {

		return sshExecWithCert(host.hostname, host.user, host.password,
				keyfile, host.port, cmd, timeout);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#rExec(net.brutex.xservices
	 * .types.HostConnection, java.lang.String, long)
	 */
	
	@WebMethod(operationName = "rExec")
	public ReturnCode rExec(@WebParam(name = "host") HostConnection host,
			@WebParam(name = "command") String cmd,
			@WebParam(name = "timeout") long timeout) {
		return rexec(host.hostname, host.port, host.user, host.password, cmd,
				timeout);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.brutex.xservices.ws.impl.ExecuteService#runTelnet(net.brutex.xservices
	 * .types.HostConnection, java.lang.String, java.lang.String,
	 * java.lang.String, long)
	 */
	
	@WebMethod(operationName = "telnet")
	public ReturnCode runTelnet(@WebParam(name = "host") HostConnection host,
			@WebParam(name = "prompt") String prompt,
			@WebParam(name = "command") String cmd,
			@WebParam(name = "expect") String expect,
			@WebParam(name = "timeout") long timeout) {
		return telnet(host.hostname, host.port, host.user, host.password, cmd,
				timeout, prompt, expect);
	}

	
	public void runJScript(String script) throws XServicesFault {

		try {
			// Create and enter a Context. A Context stores information about
			// the execution environment of a script.
			Context cx = Context.enter();
			cx.setOptimizationLevel(0);
			cx.setLanguageVersion(Context.VERSION_1_7);
			// cx is the Context instance you're using to run scripts
			/*
			 * cx.setClassShutter(new ClassShutter() { public boolean
			 * visibleToScripts(String className) {
			 * if(className.startsWith("adapter")) return true;
			 * if(className.startsWith("java.lang.System") ||
			 * className.startsWith
			 * ("org.apache.tomcat.util.log.SystemLogHandler")) return true;
			 * System.out.println(className + " is blocked."); return false; }
			 * });
			 */

			// Initialise the standard objects (Object, Function, etc.). This
			// must be done before scripts can be
			// executed. The null parameter tells initStandardObjects
			// to create and return a scope object that we use
			// in later calls.
			Scriptable scope = cx.initStandardObjects();
			// Object wrappedOut = Context.javaToJS(System.out, scope);
			// Object wrappedOut2 = Context.javaToJS(this, scope);
			// scope.put("out", scope, wrappedOut);
			// scope.put("exe", scope, wrappedOut2);

			// Execute the script
			// cx.evaluateString(scope, "importClass('java.lang.System');\n",
			// "head", 1, null);
			// cx.evaluateString(scope, "importPackage('java.util');\n", "head",
			// 2, null);
			Object obj = cx
					.evaluateString(scope, script, "TestScript", 1, null);

		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			// Exit the Context. This removes the association between the
			// Context and the current thread and is an
			// essential cleanup action. There should be a call to exit for
			// every call to enter.
			Context.exit();
		}

	}

	@WebMethod(exclude = true)
	private ReturnCode executeCommand(String executable, String[] args,
			File dir, boolean spawn, String inputstring,
			boolean newenvironment, boolean vmlauncher, boolean searchpath,
			long timeout) {
		ExecTask exe = new ExecTask();
		RunTask runner = new RunTask(exe);

		/*
		 * Commandline cmdl = new Commandline(); cmdl.setExecutable(executable);
		 * cmdl.addArguments(args); System.out.println(cmdl.describeCommand());
		 */

		exe.setExecutable(executable);
		for (String s : args) {
			exe.createArg().setValue(s);
		}

		exe.setDir(dir);
		if (spawn) {
			exe.setSpawn(spawn);
		} else {
			exe.setTimeout(timeout);
			exe.setInputString(inputstring);
			exe.setOutputproperty("ExecuteService.stdout");
			exe.setErrorProperty("ExecuteService.stderr");
			exe.setResultProperty("ExecuteService.result");
		}

		exe.setNewenvironment(newenvironment);
		exe.setVMLauncher(vmlauncher);
		exe.setSearchPath(searchpath);

		return runner.postTask();
	}

	@WebMethod(exclude = true)
	private ReturnCode sshExec(String host, String username, String password,
			int port, String command, long timeout) {
		SSHExec sshexec = new SSHExec();
		RunTask runner = new RunTask(sshexec);
		sshexec.setHost(host);
		sshexec.setUsername(username);
		sshexec.setPassword(password);
		sshexec.setPort(port);
		sshexec.setCommand(command);
		sshexec.setTrust(true);
		sshexec.setTimeout(timeout);
		sshexec.setOutputproperty("SSHExec.stdout");
		return runner.postTask();
	}

	@WebMethod(exclude = true)
	private ReturnCode sshExecWithCert(String host, String username,
			String passphrase, String keyfile, int port, String command,
			long timeout) {
		SSHExec sshexec = new SSHExec();
		RunTask runner = new RunTask(sshexec);
		sshexec.setHost(host);
		sshexec.setUsername(username);
		sshexec.setKeyfile(keyfile);
		sshexec.setPassphrase(passphrase);
		sshexec.setPort(port);
		sshexec.setCommand(command);
		sshexec.setTrust(true);
		sshexec.setTimeout(timeout);
		sshexec.setOutputproperty("SSHExec.stdout");
		return runner.postTask();
	}

	@WebMethod(exclude = true)
	private ReturnCode rexec(String host, int port, String username,
			String password, String command, long timeout) {
		RExecTask rexec = new RExecTask();
		RunTask runner = new RunTask(rexec);
		rexec.setServer(host);
		rexec.setPort(port);
		rexec.setUserid(username);
		rexec.setPassword(password);
		rexec.setCommand(command);
		rexec.setTimeout((int) Math.round(timeout));

		return runner.postTask();
	}

	@WebMethod(exclude = true)
	private ReturnCode telnet(String host, int port, String username,
			String password, String command, long timeout, String prompt,
			String expect) {
		TelnetTask rexec = new TelnetTask();
		RunTask runner = new RunTask(rexec);
		rexec.setServer(host);
		rexec.setPort(port);
		rexec.setUserid(username);
		rexec.setPassword(password);
		rexec.setTimeout((int) Math.round(timeout));

		rexec.createRead().addText(prompt);
		rexec.createWrite().addText(command);
		rexec.createRead().addText(expect);

		return runner.postTask();
	}
}
