/**
 * 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 org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 *  Class to set up the eRServer package.
 *
 * @author     ronz
 */
public class ERSUpdate extends ERS {

	/**
	 *Constructor for the ERSSetup object
	 *
	 * @param  ersHome           eRServer home directory
	 * @exception  SQLException
	 */
	public ERSUpdate(String ersHome, boolean schemaSupport) throws SQLException {

		setSchemaSupport(schemaSupport);
		Properties properties = null;

		String primaryURL;
		String primaryUser;
		String primaryPass;

		Connection primary = null;
		Connection replicant = null;
		File configFile = null;

		// Clean up ersHome
		if (!ersHome.endsWith(System.getProperty("file.separator"))) {
			ersHome += System.getProperty("file.separator");
		}

		// Read the replication.cfg file
		try {
			configFile = new File(ersHome + "etc/replication.cfg");

			if (!configFile.exists()) {
				System.out.println("Cannot find replication.cfg in " + ersHome);
				System.exit(1);
			}

			properties = new Properties();
			FileInputStream in = new FileInputStream(configFile);
			properties.load(in);
			in.close();
		} catch (IOException ix) {
			ix.printStackTrace();
			System.exit(1);
		}

		primaryURL = properties.getProperty("replic.master.JDBCConnectionURL");
		primaryUser = properties.getProperty("replic.master.user");
		primaryPass = properties.getProperty("replic.master.password");


		try {
			// Create the primary, replicant, and admin DB connections, bail if any are null
			primary = getConnection(primaryURL, primaryUser, primaryPass);

			if (primary == null) {
				System.out.println("Bad master URL/user/password");
				return;
			}

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

			String[] replicantURLs = split(properties.getProperty("replic.slave.JDBCConnectionURL"), ",");
			String[] replicantUsers = split(properties.getProperty("replic.slave.user"), ",");
			String[] replicantPasswords = split(properties.getProperty("replic.slave.password"), ",");

			for (int i = 0; i < replicantURLs.length; i++) {
				if (!quiet) {
					System.out.println("Updating slave " + replicantURLs[i]);
				}

				replicant = getConnection(replicantURLs[i], replicantUsers[i], replicantPasswords[i]);
				if (replicant == null) {
					if (!quiet) {
						System.out.println("Invalid URL. Skipping.");
					}
					continue;
				}

				try {
					updateReplicant(replicant);
				} catch (Exception ex) {
					ex.printStackTrace();
				} finally {
					try {
						replicant.close();
					} catch (Exception ex) {}
				}

			}

			if (!quiet) {
				System.out.println("\nUpdating master tables");
			}

			try {
				createView(primary);
			} catch (SQLException sx) {
				sx.printStackTrace();
			}

			if (!quiet) {
				System.out.println("Master database replication removal completed\n");
			}

			if (!quiet) {
				System.out.println("Replication function removal completed\n\n");
			}

		} finally {

			if (primary != null) {
				primary.close();
			}
		}

		if (!quiet) {
			System.out.println("eRServer update completed\n");
		}
	}

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

		Options options = new Options();
		options.addOption("q", "quiet", false, "quiet mode");
		options.addOption("d", "ers_home", true, "Install directory for eRServer (default /opt/erserver)");
		options.addOption("ns", "noschema", false, "Disable schema support (schema support in 7.3+ only)");

		//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;
		}

		// get options
		String ersHome = line.getOptionValue("d", "/opt/erserver/");

		String s = line.getOptionValue("q");
		if (s != null) {
			setQuiet(true);
		}

		boolean schemaSupport = true;

		if (line.hasOption("ns")) {
			schemaSupport = false;
		}

		try {
			new ERSUpdate(ersHome, schemaSupport);
		} catch (SQLException sx) {
			sx.printStackTrace();
		}

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

}

