/*
 *  Copyright 2013-2050 Emmanuel BRUN (contact@amapj.fr)
 * 
 *  This file is part of AmapJ.
 *  
 *  AmapJ is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.

 *  AmapJ is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with AmapJ.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 
 */
 package fr.amapj.common;

import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Permet l'execution d'une commande système avec time out
 * 
 * 
 */
public class RuntimeUtils
{

	// Passer ce paramètre à true pour activer l'affichage de la sortie du programme 
	// sur la console - A utiliser en mode développement 
	static private final boolean debug = false;
	
	
	private final static Logger logger = LogManager.getLogger();
	
	/**
	 * 
	 * @param commandLine
	 * @param timeout en milliseconds
	 */
	static public int executeCommandLine(String[] commandLine,long timeout) throws IOException, InterruptedException, TimeoutException
	{
		logger.info("Lancement de la commande="+StringUtils.asString(commandLine, " "));
		
		ProcessBuilder pb = new ProcessBuilder(commandLine);
		if (debug)
		{
			pb.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
		}
		Process p = pb.start(); 
		
		boolean done = p.waitFor(timeout,TimeUnit.MILLISECONDS);
		if (done)
		{
			int ret = p.exitValue();
			logger.info("Retour ="+ret);
			return ret;
		}
		else
		{
			p.destroy();
			logger.info("Arrêt par time out , time out ="+timeout+" ms");
			throw new TimeoutException();
		}

	}
}
