/**
 * This file is a part of Angry IP Scanner source code,
 * see http://www.azib.net/ for more information.
 * Licensed under GPLv2.
 */
package net.azib.ipscan.gui.actions;

import java.io.File;
import java.io.FileWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.azib.ipscan.config.LoggerFactory;
import net.azib.ipscan.config.Platform;
import net.azib.ipscan.core.UserErrorException;

/**
 * The cross-platform terminal launcher
 * 
 * @author Anton Keks
 */
public class TerminalLauncher {
	
	static final Logger LOG = LoggerFactory.getLogger();
	
	/**
	 * Launches the execString in the terminal.
	 * Supports Linux/Unix, MacOS, and Windows
	 * @param execString the command to launch
	 * @param workingDir the working directory (or null)
	 */
	public static void launchInTerminal(String execString, File workingDir) {

		try {
			if (Platform.WINDOWS) {
				// generate a command file :-)
				File batFile = File.createTempFile("launch", ".cmd");
				batFile.deleteOnExit();
				FileWriter writer = new FileWriter(batFile);
				writer.write("@rem This is a temporary file generated by Angry IP Scanner\n" +
						     "@start cmd /k " + execString);
				writer.close();
				
				Runtime.getRuntime().exec(batFile.getAbsolutePath(), null, workingDir);
			}
			else
			if (Platform.MAC_OS) {
				Runtime.getRuntime().exec(new String[] {"osascript", "-e", "tell application \"Terminal\" to do script \"" + execString + "\""}, null, workingDir);
			}
			else { // assume Linux or other Unix
				// TODO: maybe gnome-terminal or konsole should be tried as well...
				Runtime.getRuntime().exec(new String[] {"xterm", "-e", "bash", "-c", execString + ";bash"}, null, workingDir);
			}
		}
		catch (Exception e) {
			LOG.log(Level.WARNING, "openTerminal.failed", e);
			throw new UserErrorException("openTerminal.failed", execString);
		}
	}
}
