package com.cronos.admin.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class HttpsConfigurator {

	public static final String K_nameKeystore = "tomcatks";
	public static final String K_keyPass = "cronosdec";

	public static boolean CreateKeystore(String fullpathKeystore, String keyPass, String linuxRootPassword) {
		boolean rpta = false;

		// String nameKeystore = "tomcatks";
		// String keyPass = "cronosdec";

		String java_home = System.getProperty("java.home");
		String java_bin = java_home + File.separator + "bin";
		// String path_keystore = java_home + File.separator + "lib" +
		// File.separator + "security";
		// String fullpathKeystore = path_keystore + File.separator +
		// nameKeystore ;

		// "%JAVA_HOME%\bin\keytool.exe" -genkey -keystore
		// "%PATH_KEYSTORE%\tomcatks" -alias "tomcat" -keyalg RSA

		String commandInstruct = "";

		String sSistemaOperativo = System.getProperty("os.name");
		if (sSistemaOperativo.toLowerCase().indexOf("windows") > -1) {
			// PARA WINDOWS
			commandInstruct = "\"" + java_bin + File.separator + "keytool\" -genkey -keypass \"" + keyPass
					+ "\" -storepass  \"" + keyPass + "\" -keystore " + "\"" + fullpathKeystore
					+ "\" -alias \"tomcat\" -dName \"CN=AR\" -keyalg RSA";

		} else {
			// PARA LINUX
			commandInstruct = java_bin + File.separator + "keytool -genkey -keypass " + keyPass + " -storepass  "
					+ keyPass + " -keystore " + fullpathKeystore + " -alias tomcat -dName CN=AR -keyalg RSA";
		}

		File fKestore = new File(fullpathKeystore);

		if (!fKestore.exists())

		{
			try {
				Process pb;
				if (sSistemaOperativo.toLowerCase().indexOf("windows") > -1) {
					pb = Runtime.getRuntime().exec(commandInstruct);
				} else {
					String clave = linuxRootPassword; // "LA-CLAVE-DEL-ROOT";
					String[] cmd = { "/bin/bash", "-c", "echo " + clave + "| sudo -S " + commandInstruct };
					pb = Runtime.getRuntime().exec(cmd);
				}

				String line;
				BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
				while ((line = input.readLine()) != null) {
					System.out.println(line);
				}
				input.close();

				rpta = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			rpta = true; // Ya estaba
		}
		return rpta;
	}

}
