/**
 * Class copyright 2003 by the Ravensfield Digital Resource Group, Ltd, Granville, OH.
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without a written agreement
 * is hereby granted, provided that the above copyright notice and this
 * paragraph and the following two paragraphs appear in all copies.
 *
 * IN NO EVENT SHALL THE RAVENSFIELD DIGITAL RESOURCE GROUP, LTD BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
 * DOCUMENTATION, EVEN IF THE RAVENSFIELD DIGITAL RESOURCE GROUP, LTD HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * THE RAVENSFIELD DIGITAL RESOURCE GROUP, LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE RAVENSFIELD DIGITAL RESOURCE GROUP, LTD HAS NO OBLIGATIONS TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * (Quick readers will recognize that as the stock BSD license)
 */
package org.postgresql.ers;

import java.io.File;
import java.io.FileInputStream;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import com.postgres.replic.server.RServSignalHandler;

//the jakarta command line processing tools
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;


/**
 *  Class to send RMI-based signals to a running eRServer
 *
 * @author    Andrew Rawnsley
 */
public class ERSCtl {

	public final static String[] CMD = {"STOP", "RELOAD", "RESET"};

	static boolean quiet = false;

	/**
	 *Constructor for the ERSCtl object
	 *
	 * @param  signal  Signal to send
	 * @param  host    Host
	 * @param  port    Port
	 * @see            com.postgres.replic.server.RServSignalHandler
	 */
	public ERSCtl(int signal, String host, int port) throws RemoteException, NotBoundException {

		Registry registry = LocateRegistry.getRegistry(host, port);
		RServSignalHandler handler = (RServSignalHandler) registry.lookup("eRServer");
		if (handler != null) {
			handler.signal(signal);
		}
	}

	/**
	 * Signal the replicator
	 *
	 * @param  args  The command line arguments
	 */
	public static void main(String[] args) {

		Options options = new Options();

		options.addOption("p", "port", true, "Port # (default 1099)");
		options.addOption("h", "host", true, "Host (default localhost)");
		options.addOption("q", "quiet", false, "Run quiet");
		options.addOption("d", "ers_home", true, "Install directory for eRServer (default /opt/erserver)");

		//parse the commandline arguments
		GnuParser parser = new GnuParser();
		CommandLine line = null;
		try {
			line = parser.parse(options, args);
		} catch (org.apache.commons.cli.ParseException exp) {
			System.out.println("Parsing failed. Reason: " + exp.getMessage());
			return;
		}
		String[] cmd = line.getArgs();

		if (cmd.length == 0) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("USAGE: java org.postgresql.ers.ERSCtl <options> {stop | reset}", options);
			return;
		}

		String host;
		if ((host = line.getOptionValue("h")) == null) {
			host = "localhost";
		}

		quiet = line.hasOption("q");
		String s = line.getOptionValue("p");

		int port = -1;
		if (s != null) {
			try {
				port = Integer.parseInt(s);
			} catch (Exception ex) {
				ex.printStackTrace();
				port = -1;
			}
		}

		String ersHome = line.getOptionValue("d", "/opt/erserver/");
		if (!ersHome.endsWith("/")) {
			ersHome += "/";
		}

		if (port == -1 && host.equals("localhost")) {
			try {
				File f = new File(ersHome + "etc/replication.cfg");
				if (!f.exists()) {
					System.err.println("Cannot find " + ersHome + "etc/replication.cfg.");
					System.exit(0);
				}
				java.util.Properties properties = new java.util.Properties();
				properties.load(new FileInputStream(f));
				s = properties.getProperty("replic.rmi.port");
				if (s != null) {
					try {
						port = Integer.parseInt(s);
					} catch (Exception ex) {
						ex.printStackTrace();
						port = 1099;
					}
				} else {
					port = 1099;
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				System.exit(0);
			}
		}

		for (int i = 0; i < CMD.length; i++) {
			if (cmd[0].toUpperCase().equals(CMD[i])) {
				if (!quiet) {
					System.out.println("Signaling eRServer: " + cmd[0]);
				}
				try {
					new ERSCtl(i, host, port);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}

		if (!quiet) {
			System.out.println("\nDone\n");
		}
	}

}
