/*
 * @(#)installCA.java
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2001 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDcreator.java for details.
 *
 * Jörg Haeger, 13.06.2001
 */

import java.io.*;

class installCA
{
	public static void main(String args[])
		throws java.io.IOException
	{
		if (args.length != 1)
		{
			System.out.println("Usage: java installCA certificate");
			return;
		}

		String certificate = args[0];
		if (!new File(certificate).exists())
		{
			System.out.println(
			"The certificate file " + certificate + " does not exist!");
			return;
		}

		String
			slash = System.getProperty("file.separator"),
			alias = certificate,
			javaHome = System.getProperty("java.home"),
			keystore = javaHome + slash + "lib" + slash + "security"
				+ slash + "cacerts",
			keytool = javaHome + slash + "bin" + slash + "keytool";

		if (alias.endsWith(".der")
			|| alias.endsWith(".txt"))
			alias = alias.substring(0, alias.length() - 4);

		if (alias.indexOf(' ') >= 0)
			alias = '"' + alias + '"';

		if (certificate.indexOf(' ') >= 0)
			certificate = '"' + certificate + '"';

		if (!new File(keystore).canWrite())
		{
			System.out.println(
			"You cannot modify the file\n"
			+ "    " + keystore + "\n"
			+ "Ask the administrator of your system to run this program!");
			return;
		}

		run(keytool
			+ " -printcert"
			+ " -file " + certificate);

		System.out.print(
			"Trust the above certificate, and add it to the root CA store\n"
			+ "    " + keystore + "\n"
			+ "of your local Java Runtime Environment? [no] ");

		if (!new BufferedReader(
			new InputStreamReader(System.in)).readLine().equals("yes"))
			return;
		System.out.println("");

		if (keystore.indexOf(' ') >= 0)
			keystore = '"' + keystore + '"';

		run(keytool
			+ " -import"
			+ " -noprompt"
			+ " -keystore " + keystore
			+ " -storepass changeit"
			+ " -file " + certificate
			+ " -alias " + alias);
	}

	static void run(String command)
		throws java.io.IOException
	{
		System.out.println("Running " + command + " ...");
		Process p = Runtime.getRuntime().exec(command);
		BufferedReader reader = new BufferedReader(
			new InputStreamReader(p.getInputStream()));
		while (true)
		{
			try {
				String lineStr = reader.readLine();
				if (lineStr == null)
					break;
				System.out.println(lineStr);
			} catch (Exception e) { break; }
		}
		try {
			p.waitFor();
		}
		catch (InterruptedException e) {}
		System.out.println("");
	}
}
