package com.cronos.admin.tomcat;

import java.io.File;

public class RestartTomcat {

	public static final int tiempoEspera = 15000;
	private static String catalinaPath = "";

	public static void main(String[] args) {

		catalinaPath = args[0].replace("\"", "");

		String sSistemaOperativo = System.getProperty("os.name");
		if (sSistemaOperativo.toLowerCase().indexOf("windows") > -1) {

			// Obtenemos el nombre del Servicio Tomcat que esta corriendo
			String serviceName = WindowsServices.GetTomcatServiceName();

			// Si no hay servicio windows corriendo entonces restartemos con los
			// batch
			if (serviceName.isEmpty())
				restartWindows();
			else
				restartWindowsService();

		} else {
			restartLinux();
		}
	}

	private static void restartLinux() {

		String catalinaBinPath = catalinaPath + File.separator + "bin";
		String pathShutdown = catalinaBinPath + File.separator + "shutdown.sh";
		String pathStart = catalinaBinPath + File.separator + "startup.sh";

		File fStart = new File(pathStart);
		File fStop = new File(pathShutdown);

		if (!fStart.exists() || !fStop.exists())
			return;

		try {

			Runtime.getRuntime().exec(pathShutdown);

			/*
			 * ESTO ES PARA ELIMINAR CUALQUIER OTRA INSTANCIA DEL TOMCAT, EN CASO QUE HALLA
			 * MAS DE UNA CORRIENDO
			 */
			try {
				Runtime.getRuntime().exec(new String[] { "bash", "-c",
						"ps aux | grep -ie org.apache.catalina.startup.Bootstrap | awk \'{print $2}\' | xargs kill -9" });
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				Thread.sleep(tiempoEspera);
			} catch (Exception e) {
				e.printStackTrace();
			}

			Runtime.getRuntime().exec(pathStart);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static boolean restartWindows() {

		boolean rpta = false;

		String catalinaBinPath = catalinaPath + File.separator + "bin";
		String pathShutdown = catalinaBinPath + File.separator + "shutdown.bat";
		String pathStart = catalinaBinPath + File.separator + "startup.bat";

		File fStart = new File(pathStart);
		File fStop = new File(pathShutdown);

		if (!fStart.exists() || !fStop.exists())
			return false;

		try {

			Runtime.getRuntime().exec(pathShutdown);
			try {
				Thread.sleep(tiempoEspera);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Runtime.getRuntime().exec(pathStart);

			rpta = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rpta;
	}

	private static void restartWindowsService() {
		// HAY QUE VER COMO SACAR EL NOMBRE DEL SERVICIO
		try {
			Runtime.getRuntime().exec("net stop tomcat7");
			Thread.sleep(tiempoEspera);
			Runtime.getRuntime().exec("net start tomcat7");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}